简体   繁体   English

如何添加段落文本作为选择选项?

[英]How can I add paragraph text as select options?

I need to change the first option in the select options and put the first paragraph text inside it, so the first paragraph will be the first option text in the first select element, and the second paragraph to be the first option in the next select element.我需要更改选择选项中的第一个选项并将第一段文本放入其中,因此第一段将成为第一个选择元素中的第一个选项文本,第二段将成为下一个选择元素中的第一个选项. I know my approach is not at all correct but I tried and couldn't find the right way to do it.我知道我的方法根本不正确,但我尝试过但找不到正确的方法。 Do I need to loop?我需要循环吗? Or is there another way of doing that?或者还有其他方法吗? I'm trying using jQuery.我正在尝试使用 jQuery。

 $('.select-container p').each(function(index) { let textPar = $(this).text(); $('.select-container select option:first-child').each(function(index) { $(this).text(textPar); }); });
 select { width: 200px; padding: 5px 8px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="select-container"> <p>First paragraph</p> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> <div class="select-container"> <p>Second paragraph</p> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div>

You just need to think through your selectors a bit better.你只需要更好地考虑你的选择器。 You were updating the text of all select elements, so you need to be more specific.您正在更新所有选择元素的文本,因此您需要更加具体。 Then, you don't need to loop over one element after selecting it.然后,您无需在选择一个元素后对其进行循环。

 $('.select-container p').each(function() { const par = $(this); const parText = par.text(); par.next('select').find('option:first-child').text(parText); });
 select { width: 200px; padding: 5px 8px; }
 <div class="container"> <div class="select-container"> <p>First paragraph</p> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> <div class="select-container"> <p>Second paragraph</p> <select> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM