问题描述
说我有一张桌子,我想用它的选项更改每个选择。
因此,例如,如果表具有以下内容:
<td>
<select>
<option>first option</option>
<option selected>second option</option>
<option>third option</option>
</select>
</td>
它应该变成这个:
<td>
second option
</td>
这是我尝试过的:
$('#table select').find(":selected").each(function() { this.replaceWith(this.text()); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> <html> <body> <table id="table"> <thead> <th>test</th> </thead> <tbody> <tr> <td> <select> <option>first option</option> <option selected>second option</option> <option>third option</option> </select> </td> </tr> <tr> <td> <select> <option>first option</option> <option>second option</option> <option selected>third option</option> </select> </td> </tr> </tbody> </table> </body> </html>
但是我得到this.text is not a function
,如何指出选择项的文本?
我迷路了。
1楼
您发现this
关键字引用了选定的元素。
但是text
是一个jQuery功能,不存在作为一个方法, this
。
为了能够使用this
和jQuery,您需要将其包装到$(this)
。
使用parents
选择TD
,然后使用text
进行更改。
如您的示例所提供的那样,这将获得期望的结果。
$('#table select').find(":selected").each(function() { $(this).parents("td").text($(this).text()); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <table id="table"> <thead> <th>test</th> </thead> <tbody> <tr> <td> <select> <option>first option</option> <option selected>second option</option> <option>third option</option> </select> </td> </tr> <tr> <td> <select> <option>first option</option> <option>second option</option> <option selected>third option</option> </select> </td> </tr> </tbody> </table> </body> </html>
香草解决方案(无jQuery)
//Vanilla solution //Array.from: casts a node list (array like) to actual Array; supported by all major browsers except IE //querySelector is used to select the elements. Then loop with array's forEach Array.from(document.querySelectorAll("#table select > option:checked")).forEach(function(element) { //element refers to the selected element //go up two elements to the TD and save to parent var parent = element.parentElement.parentElement; //use replaceChild and createTextNode //createTextNode creates a node from the string provided. var textNode = document.createTextNode(element.textContent); //replace from the parent parent.replaceChild(textNode, parent.querySelector("select")); });
<html> <body> <table id="table"> <thead> <th>test</th> </thead> <tbody> <tr> <td> <select> <option>first option</option> <option selected>second option</option> <option>third option</option> </select> </td> </tr> <tr> <td> <select> <option>first option</option> <option>second option</option> <option selected>third option</option> </select> </td> </tr> </tbody> </table> </body> </html>