我正在使用JQuery动态(基于用户选择)创建标记.用户在文本框中输入require选项,我的代码创建了它的select标签.脚本是:
var numbersString = "1,2,3,4,5,6";
var data = numbersString.split(',');
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#msj_form");
Run Code Online (Sandbox Code Playgroud)
其中msj_form是标签附加的div id.现在它创建:
<select id="selectId" anme="selectName">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
</select>
Run Code Online (Sandbox Code Playgroud)
但我也希望将标签和<tr><td>代码与标签结合起来,使代码看起来像:
<tr>
<td>My Label</td>
<td>
<select id="selectId" anme="selectName">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
<option value="3">4</option>
<option value="4">5</option>
<option value="5">6</option>
</select>
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

Rav*_*dag 45
var s = $("<select id=\"selectId\" name=\"selectName\" />");
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
Run Code Online (Sandbox Code Playgroud)
在for循环之后,用TableRow和Cells包装所有内容,像这样,Jquery Wrap()
$(s).wrap('<table><tr><td></td></tr></table>');
Run Code Online (Sandbox Code Playgroud)
<!-- Create Dropdown -->
/* 1- First get total numbers of SELECT tags used in your page to avoid elements name/id issues.
* 2- Get all OPTIONS user entered with comma separator into a text box.
* 3- Split user OPTIONS and make an array of these OPTIONS.
* 4- Create SELECT code.
* 5- Appent it into the temp div (a hidden div in your page).
* 6- Then get that code.
* 7- Now append code to your actual div.
* 8- Filnally make empty the temp div therfore it will be like a new container for next SELECT tag.
*/
total = $("select").size() + 1; // 1-
var myoptions = $("#myoptions").val(); // 2-
var data = myoptions.split(','); // 3-
var s = $("<select id=\""+total+"\" name=\""+total+"\" />"); // 4-
for(var val in data) {
$("<option />", {value: val, text: data[val]}).appendTo(s);
}
s.appendTo("#tempselect"); // 5-
var getselectcode = $("#tempselect").html(); // 6-
$("#msj_form").append(appendLabel+"<td>"+getselectcode+"</td></tr>"); // 7-
$("#tempselect").html(''); // 8-
<div style="display:none;" id="tempselect"></div> // Temp div
Run Code Online (Sandbox Code Playgroud)