如何使用className(javascript)在div标签上应用onclick

时间:2018-07-28 10:53:20

标签: javascript jquery

我有一个像这样的div

div class="ncf-container nfc-bottom-right">
<div class="ncf info">
<button>X</button>
<p class="nfc-message">New Notification</p>
</div>
</div>

如何使用类名(Javascript)在div上应用onclick

3 个答案:

答案 0 :(得分:0)

以下是使用eventJquery添加javascript的方法。

var classname = document.getElementsByClassName("nfc-bottom-right");
var myFunction = function() {
    alert('clicked javascript way');
};
for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}


$(".nfc-bottom-right").on("click",function(){
  alert('Jquery way');
})
.nfc-bottom-right{
 border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="ncf-container nfc-bottom-right">
<div class="ncf info">
<button>X</button>
<p class="nfc-message">New Notification</p>
</div>
</div>

答案 1 :(得分:0)

jQuery

$('info').on('click', function() { // ... your code to execute onClick });

香草JS

document.querySelector('.info').addEventListener('click', function() { // ... your code to execute onClick });

答案 2 :(得分:0)

您可以通过以下方式通过类名称为div标签指定onclick行为:

<!-- This is your div, with custom class name -->
<div class="yourClassName">
Div Content
</div>

<script>
     document.querySelector('.yourClassName')
     .addEventListener('click', function() {

       // This is the logic that is run when the div with yourClassName class is clicked
       alert('the div was clicked');
     })
</script>