我对如何处理以下内容感到有点困惑(我能想到的唯一解决方案是手动编写每一个这样的事件,但这不可扩展/实用,因为页面可能是动态的) - 这是原始的jQuery代码,它处理一个ID很简单的表单(效果很好):
$('#resultTable').on("click", "#frm", function() {
$('#updateButton').show();
$("#successStr").empty();
});
但是,如果我想拥有多个表单,每个表单都有自己的ID(即#frm1,#frm2等),并且动态地将该ID后缀(1,2等)作为子/的一部分,该怎么办?相关ID?这样的事情(resultTable有多个表单,每个表单都有一个更新按钮等):
$('#resultTable').on("click", "[id^='frm']", function() {
$('#updateButton'+XXX).show();
$("#successStr"+XXX).empty();
});
其中XXX是来自父#frmID号的后缀ID号(可能是“捕获”正则表达式来自()上父级的号码?)
任何有关如何处理此事的提示都将受到赞赏。
由于
答案 0 :(得分:0)
为表单使用frm_n,为控件使用updateButton_n,即
frm_1 => updateButton_1,frm_2 => updateButton_2 ...
$('#resultTable').on("click", "[id^='frm_']", function() {
$('#updateButton_'+ $(this).attr("id").split("frm_")[1]).show();
$("#successStr_"+ $(this).attr("id").split("frm_")[1]).empty();
});
答案 1 :(得分:0)
您没有显示HTML
标记,但下面的解决方案应该稍作调整(以适合您当前的布局):
$(function () {
// When clicking any form with class = myForm
$('#resultTable').on("click", ".myForm", function () {
// Look for the button with class = myUpdateButton that's
// within this form
$('.myUpdateButton', $(this)).show();
// Look for the element with class = mySuccessStr that's
// within this form
$('.mySuccessStr', $(this)).empty();
});
});
/* Just for this example */
.myForm {
border: 1px solid #000;
}
/* The buttons will be hidden at first */
.myUpdateButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultTable">
<form class="myForm">
<button class="myUpdateButton">Update</button>
<span class="mySuccessStr">Success!</span>
</form>
<br />
<form class="myForm">
<button class="myUpdateButton">Update</button>
<span class="mySuccessStr">Success!</span>
</form>
</div>
另一个解决方案是依赖data
属性:
$(function () {
// When clicking any form with class = myForm
$('#resultTable').on("click", ".myForm", function () {
var dataRel = $(this).data('rel');
// Look for the button with class = myUpdateButton which
// data-rel matches this form
$('.myUpdateButton[data-rel=' + dataRel + ']').show();
// Look for the element with class = mySuccessStr which
// data-rel matches this form
$('.mySuccessStr[data-rel=' + dataRel + ']').empty();
});
});
/* Just for this example */
.myForm {
border: 1px solid #000;
}
/* The buttons will be hidden at first */
.myUpdateButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultTable">
<!-- Scenario where the elements are not within the form -->
<form class="myForm" data-rel="f1">
<br />
<br />
</form>
<br />
<button class="myUpdateButton" data-rel="f1">Update</button>
<span class="mySuccessStr" data-rel="f1">Success!</span>
<br />
<form class="myForm" data-rel="f2">
<br />
<br />
</form>
<button class="myUpdateButton" data-rel="f2">Update</button>
<span class="mySuccessStr" data-rel="f2">Success!</span>
</div>