How to get multiple html controls to use the same event handler
I have some javascrip开发者_运维技巧t and am creating some html on the fly. 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. How can I change the code so that all the controls will fire the same event?
I'd use the .live method
rule_selected: function () {}
add a class selectable
to your rules and add the live event before creating/deleting your rules items
$(".selectable").live("click", rule-selected);
If you really want to use the id of your rules, i'd look into your usage of ids; 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.
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>
精彩评论