use*_*188 5 html javascript jquery select
我想知道为什么在我调用replaceWith之后,jQuery的.val() 函数没有<select>为我设置控件的值,但是它可以正常工作。
<select><option>ABC</option><option>DEF</option></select>
<input type="button" onclick="ControlOff()" value="Turn Off Control" />
<input type="button" onclick="ControlOn()" value="Turn On Control" />
<input type="button" onclick="Test()" value="Value Setting Test" />
function ControlOff() {
$('select').each(function () {
$(this).replaceWith('<span class="select-type">' + $(this).val() + '</span>');
});
}
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
$(this).replaceWith('<select><option>ABC</option><option>DEF</option></select>');
$(this).val(selected);
});
}
function Test() {
$('select').val('DEF');
}
Run Code Online (Sandbox Code Playgroud)
问题是ControlOn你有一个each正在循环的.select-type元素,而spans 和 span 不能用该方法设置val:
您可以通过将方法更改为以下方式来解决此问题:
function ControlOn() {
$('.select-type').each(function () {
var selected = $(this).text();
var $select = $('<select><option>ABC</option><option>DEF</option></select>');
$(this).replaceWith($select)
$select.val(selected);
});
}
Run Code Online (Sandbox Code Playgroud)
实例: http: //jsfiddle.net/qSYYc/4/