简体   繁体   中英

Javascript Onclick div class

So I have a button that is a div class, lets call it "login-button-arrow". I want to set up a javascript method, so when this div gets clicked on, a little javascript box can pop up.

How do I go about doing this? I have tried something like this:

login-button-arrow.onclick{alert('xyz')}

but I guess it does not work like that.

jsBin demo

// Cache your elements:
var $lba= document.getElementsByClassName('login-button-arrow');

// You nice function:
function myPopup() {
    alert( "xyz" );
}

// Assign a click event handler to every element:
for(var i=0; i<$lba.length; i++) {
    $lba[i].onclick = myPopup;
}

Also see: http://caniuse.com/getelementsbyclassname and eventually https://gist.github.com/eikes/2299607 if you need to support IE6 :)

A somewhat newer JS version of the above would be (lacks support in IE8):

var $lba= document.querySelectorAll('.login-button-arrow');

function myPopup() {
    alert( "xyz" );
}

for(var i=0; i<$lba.length; i++) {
    $lba[i].addEventListener("click", myPopup, false);
}

ES6 would look like: jsBin demo

function myPopup() {
  alert( "xyz" );
}

const buttons = document.querySelectorAll('.login-button-arrow');
[...buttons].map( btn => btn.addEventListener("click", myPopup));
$('.login-button-arrow').on('click', function() { alert('xyz'); });
var login-button-arrows = document.getElementsByClassName('login-button-arrow');

login-button-arrows.forEach(function(obj){
    obj.addEventListener('click', function(){
        alert('xyz');
    });
});

using Jquery :

$('#login-button-arrow').on('click', function(){ alert('xyz'); });

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