我在ajax调用后获取html,我想将输出更改为选项。我选择了要附加这些选项的标签
<div class="views-element-container">
<div class="view view-contact-view-id-contact view-display-id-page_2 js-view-dom-id">
<div class="view-content">
1009abc example 1008xyz example
</div>
</div>
</div>
现在我想要输出:
<option value="1009">abc example </option>
<option value="1008">xyz example </option>
您可以使用片段和正则表达式
const str = `<div class="views-element-container"><div class="view view-contact-view-id-contact view-display-id-page_2 js-view-dom-id">
<div class="view-content">
1009abc example 1008xyz example
</div>
</div>
</div>`
const sel = document.querySelector("select");
const fragment = document.createElement("div");
fragment.innerHTML = str;
const re = /(\d+)(\w+)\s+(\w+)/g;
let text = fragment.querySelector(".view-content").textContent.trim().match(re)
console.log(text)
let match;
let optionsHTML = [];
while ((match = re.exec(text)) !== null) {
const [_, id, name, value] = match;
const displayText = `${name} ${value}`;
optionsHTML.push(`<option value="${id}">${displayText}</option>)`);
}
sel.innerHTML += optionsHTML.join(""); // or use createElement or new Options to not allow XSS
<select>
<option value="">Please select</option>
</select>