append() 方法
append() 方法在被选元素的末尾插入指定的内容。
append() 和 appendTo() 方法的执行方式相同。
它们之间的区别在于特定于语法的内容和目标的位置。
使用 prepend() 方法在所选元素的开头插入内容。
在本教程中,我们将找出使用 jQuery 从 JavaScript 对象向 select 元素添加选项的最佳方法。
让我们讨论每种方法并尝试一起解决问题。
第一种方法是将选项标签添加到选择框。
选项标签像 HTML 字符串一样创建,选择框是用 jQuery 选择器选择的。
该选项是通过 append() 方法添加的。
此方法将指定的内容作为 jQuery 集合的最后一个子元素插入,从而将选项添加到 select 元素中。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.5.0.min.js"> </script> </head> <body> <p> Select one of the proposed options: <select id="selectId"> <option value="firstEl">First Element</option> <option value="secondEl">Second Element</option> </select> </p> <button onclick="addOption()"> Add Element </button> <script type="text/javascript"> function addOption() { optText = 'New elemenet'; optValue = 'newElement'; $('#selectId').append(`<option value="${optValue}">${optText}</option>`); } </script> </body> </html>
第二种方法使用 Option() 构造函数来创建新选项。
Option() 构造函数用于创建新的选项元素。
要创建新选项,将使用文本和值参数。
然后,使用 append() 方法将元素添加到选择框:
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.5.0.min.js"> </script> </head> <body> <p> Select one of the proposed options: <select id="selectId"> <option value="firstEl">First Element</option> <option value="secondEl">Second Element</option> </select> </p> <button onclick="addOption()"> Add Element </button> <script type="text/javascript"> function addOption() { optText = 'New Element'; optValue = 'newElement'; $('#selectId').append(new Option(optText, optValue)); } </script> </body> </html>
第三种方法是使用选项标签创建一个新的 jQuery DOM 元素。
标签的值用 val() 方法指定,文本用 text() 方法指定。
其中我们还应该使用 append() 方法将元素添加到选择框。
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.5.0.min.js"> </script> </head> <body> <p> Select one of the proposed options: <select id="selectId"> <option value="firstEl">First Element</option> <option value="secondEl">Second Element</option> </select> </p> <button onclick="addOption()"> Add Element </button> <script type="text/javascript"> function addOption() { optText = 'New element'; optValue = 'newElement'; $('#selectId') .append($('<option>').val(optValue).text(optText)); } </script> </body> </html>
日期:2020-06-02 22:16:07 来源:oir作者:oir