简体   繁体   中英

Getting the contents of a div using on-click functions

I am currently trying to implement a "button" of sorts using javascript. When a user clicks on the div, the div background should change colors, and there should be a pop up listing the device number. I am planning on using the number to redirect the client later. But right now, I can't get the clicking event to register. I had the event working correctly for a bit, but the value was always the final value of 'i'. My webpage also has JQuery in it.

Here's a JSFiddle and my relevant code. http://jsfiddle.net/G3ADG/9/

HTML Structure:

<div class="device" id="device1" value="1">
    <div class="device-name" id="deviceName1">Name1</div>
</div>
<div class="device" id="device2" value="2">
    <div class="device-name" id="deviceName2">Name2</div>
</div>
<div class="device" id="device3" value="3">
    <div class="device-name" id="deviceName3">Name3</div>
</div>

Javascript:

(function() {
    var devices = document.getElementsByClassName("device");
    for (var i = 0; i < devices.length; i++) {
        devices[i].addEventListener("click", function () {
            alert(i);
            this.style.backgroundColor = "#000000";
        })
    }
})();

Any help or input is appreciated.

EDIT: Fixed the ClassName call. The alert returned is still wrong though.

If you are already using jQuery - What you are trying can be done with this -

$('.device').on('click',function(){
   $(this).css('background-color','red');
})

Demo ---> http://jsfiddle.net/G3ADG/8/

Check this fiddle :

You just needed a closure to attach events

(function () {
    var devices = document.getElementsByClassName("device");
    for (var i = 0; i < devices.length; i++) {
        (function (i) {
            devices[i].addEventListener("click", function () {
                alert(i);
                this.style.backgroundColor = "#000000";
            })
        })(i);
    }
})();

Instead of running a for loop, just run $('.device').each() . I also added an alert to get each div.device 's value. See here: http://jsfiddle.net/G3ADG/10/

Edit: I did it with bind instead of an on click because that mirrored how he was doing it in plain JS. pXL's solution using on works just as well if you are not dynamically adding div.device .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM