jquery - How do I bind Javascript events to dynamic classes -
i need generate background color change members of same class when member of class has mouseover.
here's javascript:
var array = ['abc','def','abc','xyz']; var row; var cell = []; var rowclass = []; (var = 0; < array.length; i++){ // insert empty <tr> element row = document.getelementbyid("mytable").insertrow(i+1); // insert cells <td></td> for(var j = 0; j < 2; j++){ cell[j] = row.insertcell(j); }; // fill cells <td></td> cell[0].innerhtml = 'row ' + i; cell[1].innerhtml = array[i]; cell[1].setattribute("class", array[i]); } var k0 = 0; rowclass[k0] = '.' + array[k0]; $(document).on('mouseover', rowclass[k0] ,function() {$(rowclass[k0]).css("background-color", "yellow");}); $(document).on('mouseout', rowclass[k0] ,function() {$(rowclass[k0]).css("background-color", "");}); var k1 = 1; rowclass[k1] = '.' + array[k1]; $(document).on('mouseover', rowclass[k1] ,function() {$(rowclass[k1]).css("background-color", "yellow");}); $(document).on('mouseout', rowclass[k1] ,function() {$(rowclass[k1]).css("background-color", "");}); var k2 = 2; rowclass[k2] = '.' + array[k2]; $(document).on('mouseover', rowclass[k2] ,function() {$(rowclass[k2]).css("background-color", "yellow");}); $(document).on('mouseout', rowclass[k2] ,function() {$(rowclass[k2]).css("background-color", "");}); var k3 = 3; rowclass[k3] = '.' + array[k3]; $(document).on('mouseover', rowclass[k3] ,function() {$(rowclass[k3]).css("background-color", "yellow");}); $(document).on('mouseout', rowclass[k3] ,function() {$(rowclass[k3]).css("background-color", "");});
here jsfiddle.
how replace 4 explicit 'on' statements hack proper code? after trying loops , various answers suggest on stack overflow, best work.
how replace 4 explicit 'on' statements hack proper code? after trying loops ...
you can use hover event instead of mouseover
& mouseout
. reason why did not work in loop because trying use index i
in event call back. here fiddle demonstrates problem.
i think arguably cleaner way write code. explanation in-lined comments.
jquery(function($) { var table = $('#mytable'), classes = ['abc', 'def', 'abc', 'xyz']; $.each(classes, function(index, class_name) { // create table row , append 2 table cells var tr = $('<tr>').append([ $('<td>', { 'text': 'row ' + index }), $('<td>', { 'text': class_name, 'class': class_name }).hover( // replaces mouseover hovereffect('yellow', class_name), // replaces mouseout hovereffect('inherit', class_name) ) ]); table.append(tr); }); function hovereffect(color, class_name) { // function must returned hover effect work return function() { // function closes on color , class_name $('.' + class_name).css('background-color', color); }; } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <table id="mytable" width="100" cellpadding="3" border="1"> <tr> <td>column1</td> <td>column2</td> </tr> </table>
Comments
Post a Comment