当类名相同时,单击事件不起作用

时间:2017-01-12 09:14:13

标签: javascript jquery html css

为什么点击事件在这里不起作用?我的错是什么?



$(document).ready(function() {
  $('.dashboardList').click(function() {
    alert("hello");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="dashboardList unread">
<div class="dashboardList unread">
<div class="dashboardList unread">
<div class="dashboardList unread">
<div class="dashboardList unread">
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:2)

您的divs为空,未关闭。

先关闭它们

&#13;
&#13;
$(document).ready(function() {
  $('.dashboardList').click(function() {
    alert("hello");
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="dashboardList unread">test</div>
<div class="dashboardList unread">test</div>
<div class="dashboardList unread">test</div>
<div class="dashboardList unread">test</div>
<div class="dashboardList unread">test</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以关注.on() jQuery的功能。

jQuery的官方文档:http://api.jquery.com/on/

运行下面的示例,希望它有所帮助:

&#13;
&#13;
// Waiting for DOM's load
$(document).ready(function(){
    // Binding the event and it's callback to the selector
    $('.dashboardList').on('click', function(){
        // Exposing the clicked div's content
        alert($(this).text());
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dashboardList unread">test 1</div><br />
<div class="dashboardList unread">test 2</div><br />
<div class="dashboardList unread">test 3</div><br />
<div class="dashboardList unread">test 4</div><br />
<div class="dashboardList unread">test 5</div><br />
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您的HTML不完整,请将您的HTML修改如下:

$(document).ready(function() {
  $('.dashboardList').click(function() {
    alert("hello");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="dashboardList unread">1</div>
<div class="dashboardList unread">2</div>
<div class="dashboardList unread">3</div>
<div class="dashboardList unread">4</div>
<div class="dashboardList unread">5</div>

答案 3 :(得分:0)

检查此垃圾箱,似乎一切正常

http://jsbin.com/kicikojuza/edit?html,css,js,output

我只关闭所有div

<div class="dashboardList unread">one</div>
<div class="dashboardList unread">two</div>
<div class="dashboardList unread">tree</div>
<div class="dashboardList unread">for</div>
<div class="dashboardList unread">five</div>

并添加一些日志提醒

$(document).ready(function(){
    $('.dashboardList').click(function(e){
        alert("hello, i'm " + e.target.innerText);
    });
});