我搜索了类似的问题,我找到了一些,但他们的解决方案对我没有帮助。 例如:
我的问题是:
我有一个表,用户可以动态添加行,所以我为每一行和内部的所有元素创建一个唯一的id。 每行有两个文本字段并选择两个选项,当你选择其中一个选项时,文本字段应该是dislpay:block而第二个将显示:“none”,具体取决于你的选择。
我在这里构建了一些示例,它将显示一般结构(JSFiddle)
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>
<input id="description-first-1" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-1" name="description-second-2" type="text" placeholder = "second">
<select id="select-1">
<option>
<option id="first-opt-1">1</option>
<option id="second-opt-1">2</option>
</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="description-first-2" name="description-first-1" type="text" placeholder = "first">
<input id="description-second-2" name="description-second-2" type="text" placeholder = "second">
<select id="select-2">
<option>
<option id="first-opt-2">1</option>
<option id="second-opt-2">2</option>
</option>
</select>
</td>
</tr>
$(function() {
$("#select-1").change(function() {
if ($("#first-opt-1").is(":selected")) {
$("#description-first-1").show();
$("#description-second-1").hide();
} else {
$("#description-first-1").hide();
$("#description-second-2").show();
}
}).trigger('change');
});
http://jsfiddle.net/8vz121rq/9/
在我的例子中你可以看到只有2行,但它也可以是10行,具有不同的id。
如果所有元素的id都是动态的,如何让jquery识别哪一行及其中的所有元素?
答案 0 :(得分:1)
首先,您需要事件委派,因为行是动态生成的,例如:
$("table").on("change", "[id^='select']", function() {
// do your stuf
});
或者在你的情况下:
$("table").on("change", "#select-1", function() {
// do your stuf
});
那么,这就是你需要的吗?
$(function() {
$("table").on("change", "[id^='select']", function() {
var $this = $(this);
var $row = $this.closest("tr");
var ID = this.id.replace(/^[^\-]+\-(\d+)$/gi, '$1');
var sIndex = $this.prop('selectedIndex');
var part = sIndex === 2 ? "second" : "first";
if (!sIndex) {
$row.find("input").show();
return;
}
$row.find("input").hide();
$row.find("#description-" + part + "-" + ID).show();
});
});
演示@ Fiddle
P.S。以上内容完全基于您的标记和ID结构!