[英]How to get multiple html controls to use the same event handler
I have some javascript and am creating some html on the fly. 我有一些JavaScript,并且正在即时创建一些html。 What I want to do is add an event handler to each control (they are all “Input” controls) so that if I click on any of them they all fire the same event.
我想做的是向每个控件(它们都是“输入”控件)添加一个事件处理程序,这样,如果我单击它们中的任何一个,它们都将触发相同的事件。 I first define a delegate in the initialize section of the code like this:
我首先在代码的初始化部分中定义一个委托,如下所示:
this.rule_event_handler = Function.createDelegate(this, this.rule_selected);
I have a function shown below that I want all the controls to call when clicked: 我有一个下面显示的函数,我希望所有控件在单击时都可以调用:
rule_selected: function () {}
I add the handler as shown below: 我添加处理程序,如下所示:
display_rules: function () {
var rulearea = $('#ruleControlArea')[0];
rulearea.innerHTML = "";
for (intI = 0; intI < this.arrRules.length; intI++) {
rulearea.innerHTML += this.create_rule_control(intI, this.arrRules[intI].display);
$addHandlers($('#rule_' + intI)[0], { 'click': this.rule_event_handler }, this, true);
}
},
The problem I then see is that only the last control cause the onclick event to fire. 然后我看到的问题是,只有最后一个控件才导致触发onclick事件。 How can I change the code so that all the controls will fire the same event?
如何更改代码,以便所有控件将触发同一事件?
I'd use the .live method 我会用.live方法
rule_selected: function () {}
add a class selectable
to your rules and add the live event before creating/deleting your rules items 在创建/删除规则项之前,为规则添加
selectable
的类并添加实时事件
$(".selectable").live("click", rule-selected);
If you really want to use the id of your rules, i'd look into your usage of ids; 如果您真的想使用规则的ID,我将调查您对ID的用法; it looks like you're using the same id many times on the page (you're using the id query as an array, which i find strange; any specific reason for that?) and that may cause weird behavior.
看来您在页面上多次使用相同的ID(您将ID查询用作数组,我觉得很奇怪;是否有任何特定原因?),这可能会导致奇怪的行为。
EDIT 编辑
here is a sample 这是一个样本
<div id="RulesControlArea">
</div>
<div id="AddRule">Add Rule</div>
<div id="DisplayRules">Display Rules</div>
<script type="text/javascript">
function display_rules() {
var rulearea = $('#RulesControlArea');
rulearea.empty();
for (intI = 0; intI < 10; intI++) {
rulearea.append("<div id='" + Math.random() + "." + intI + "' class='selectable'>this is a rule from display_rules</div>");
}
}
$("#RulesControlArea .selectable").live('click', function(element) { alert(element.target.innerHTML); });
$("#AddRule").click(function() { $("#RulesControlArea").append("<div id='" + Math.random() + "' class='selectable'>this is a rule</div>"); });
$("#DisplayRules").click(display_rules);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.