【发布时间】:2014-03-31 21:24:55
【问题描述】:
我一直在绞尽脑汁想弄清楚为什么 jQuery 没有响应。但我已经弄清楚为什么这是因为我下面的表单是由 javascript 动态创建的,而不是在 DOM 内部。
如果我使用$(this).css("border", "1px solid red"); 来定位输入文本字段,它可以工作并产生效果,但是当我使用next() 时似乎找不到它,我认为是因为它是动态HTML。
如何定位 元素?
<!-- Pretend this modal box is empty. The <form> is dynamically loaded when a button is clicked -->
<div id="modal_box">
<form id="form_a">
<input type="text"><b></b>
<input type="text" class="required"><b></b>
<input type="text"><b></b>
<br>
<button onclick="validate('form_a')"> Go </button>
</form>
</div>
<script>
function validate(whichform) {
var valid = true;
// whichform is the id so use id selector here
$('#' + whichform + " .required").each(function (i) {
if ($(this).val().length == 0) {
$(this).css("border", "1px solid red");
$(this).next("b").html("Required field");// should I be using next()? or something else to find dynamically loaded HTML elements?
valid = false
}
else {
$(this).css("border", "1px solid black");
$(this).next("b").html("");
}
});
// Return the valid state
return valid;
}
</script>
【问题讨论】:
-
"我应该使用 next()",是的 next 就足够了。
标签: jquery dynamic selector elements targeting