将ajax输出隐藏到选项中

问题描述 投票:0回答:1

我在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>
jquery ajax
1个回答
0
投票

您可以使用片段和正则表达式

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>

© www.soinside.com 2019 - 2024. All rights reserved.