【发布时间】:2017-05-31 16:54:06
【问题描述】:
我在两个输入文本元素(即readonly)和两个按钮上使用JQuery,这样当单击按钮1 时仅输入1 应该变为读/写。并且,当单击按钮 2 时,only 输入 2 应该变为读/写。并且当再次单击相应的按钮时,相应的输入应该再次变为只读。但是无论单击哪个按钮,我的以下脚本都会更改两个输入的只读属性。我认为应该只为该特定输入触发一个事件,正如用户 here 此处所解释的那样。
注意:我知道我们可以使用 id 代替类选择器,但在我的实际场景中,输入和按钮标签是通过循环动态生成的,数据来自数据库。因此,我们不知道每次会创建多少这样的元素。而且,正如上述链接中的用户指出的那样,对应的按钮只应触发一次单击事件。因此,问题实际上是我们如何实现这种情况,因为下面给出的示例在这种情况下不起作用。
HTML:
<table>
<tbody>
<tr>
<td>
<input class="txtInput" type="text" name="test1" value="test1val" readonly/>
</td>
<td>
<input type="button" class="btnEdit" name="editName" value="Edit"/>
</td>
</tr>
<tr>
<td>
<input class="txtInput" type="text" name="test2" value="test2val" readonly />
</td>
<td>
<input type="button" class="btnEdit" name="editName" value="Edit" />
</td>
</tr>
</tbody>
</table>
JQuery:
$(document).ready(function () {
$('.btnEdit').click(function () {
if ($('.txtInput').prop('readonly')) {
$('.txtInput').removeAttr('readonly');
}
else {
$('.txtInput').attr('readonly', 'readonly')
}
});
});
页面展示:
【问题讨论】:
标签: javascript jquery html css