开发者

Mixing CSS & Javascript Eventhandlers

I'd like to be able to assign the same event handler to a number of different div elements. Each element will have a unique style.

I registered the eventhandler like so:

<script type="text/javascript">

function add_something() {
    document.getElementById('manipulate').onclick = do_something; 
}

function do_something(e) { 
this.style.property = value;
}

w开发者_JAVA百科indow.onLoad = add_something;
</script>

So I can assign an event handler to an element like so:

<div id="manipulate"></div>

The problem is that I want to assign that handler to several elements, each with a unique style, and I want to use CSS to do it. but i'm not sure how to do that.

Eventually, I want something that looks like this:

 <style>
 #element1{...}
 #element1{...}
 #element1{...}
 </style>

.....

<div id="element1" class="manipulate"></div>
<div id="element2" class="manipulate"></div>
<div id="element3" class="manipulate"></div>

Is this possible? Thanks


Event delegation?

HTML:

<div id="wrap">
    <div id="element1" class="manipulate">First element</div>
    <div id="element2" class="manipulate">Second element</div>
    <div id="element3" class="manipulate">Third element</div>
</div>

JavaScript:

var wrap = document.getElementById('wrap');

wrap.onclick = function (e) {
    var elem = e.target;

    elem.style.color = 'red';
};

Live demo: http://jsfiddle.net/VLcPw/


You can select elements by class in modern browsers, or just use jQuery and know it works everywhere.

$(document).ready(function(){
   $('.manipulate').click(function(){alert('Hello.')});
   //or .hover/any other event.
});

jQuery events.

Perhaps a more relevant example?

$('.manipulate').click(function(){
   $(this).addClass( 'whateverClass' );
   //or
   $(this).css('color', 'red');
});


Why are you not giving jquery a try?

With jquery you should just need this to bind the same click event to all corresponding elements:



    $("div.manipulate").click(function(e) {
        $(this).css(property, value);
    });

property has to replaced with a valid css property, value with a correct value, of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜