【发布时间】:2014-03-14 10:51:02
【问题描述】:
我正在使用 Ajax 动态插入一些 <input type='text'> 元素,但是当我更新它们时,value 实际上并未在 DOM 中更新。
假设我有一个值为old 的字段,然后用新值new 更新它...如果我在Chrome 控制台中写入alert($("input[value='new']").val());(当然是在更新之后)它只是带有undefined 提示,但我仍然可以搜索old 值!?
请查看我的 JSFiddle demo 了解我的问题。如果您不更改 <input type='text'> 值,而只是更改 <select> 选项,一切正常,我可以看到哪些组是某个选项的成员,但如果我更改 <input type='text'> 则它不起作用没有了。
请注意,$(document).on("change"... 是必需的,因为元素来自 Ajax 调用。
HTML:
<p>
<input type="text" value="Group 1" data-id='123' />
<select multiple>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</p>
<p>
<input type="text" value="Group 2" data-id='abc' />
<select multiple>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</p>
<hr>
<ul class="group" data-id='123'> <span>Group 1</span>
<ul class="item"><span>Item 1</span></ul>
<ul class="item"><span>Item 2</span></ul>
</ul>
<ul class="group" data-id='abc'> <span>Group 2</span>
<ul class="item"><span>Item 3</span></ul>
<ul class="item"><span>Item 4</span></ul>
</ul>
<hr>
<div></div>
jQuery/JS:
// When changing INPUT:TEXT then update the UL>SPAN text based on the "data-id" attribute
$(document).on("change", "input", function () {
var group = $(this).val();
var id = $(this).data("id");
$("ul[data-id='" + id + "'] span:first").text(group);
});
// When changing either INPUT:TEXT or SELECT then update the list of assocuated groups
$(document).on("change", "select, input", function () {
// Empty the debug DIV text
$("div").text("");
// Show all options from the first SELECT
$("select:first option").each(function () {
var txtOptionAvailable = $(this).text();
$("div").append("<p><strong>" + txtOptionAvailable + "</strong></p>");
// Show all groups
$(".group > span").each(function () {
var txtGroup = $(this).text();
$("div").append("<p>Processing " + txtGroup + "</p>");
$("input[value='" + txtGroup + "']").next().find("option:selected").each(function () {
var txtOptionSelected = $(this).text();
// If the "available option" matches the "selected option"
if (txtOptionAvailable == txtOptionSelected) {
$("div").append("<p>" + txtGroup + " has selected " + txtOptionSelected + "</p>");
}
});
});
});
});
谁能看出我做错了什么?
【问题讨论】:
标签: jquery