【问题标题】:Click on the current div in jquery not working单击jquery中的当前div不起作用
【发布时间】:2013-07-29 22:47:44
【问题描述】:

帮助,解决方法:

http://jsfiddle.net/guin90/mb5BJ/2/

$("#click").on("click", function(){
    if($(this).attr("thesame") == 1){
        // Performs div is clicked on it and not on other elements within it. 
        // It's not working!
    } else {      
        return false;
    }

    alert("Hellow");
    $(this).css("background", "red");

    // Only if you clicked the div # click and not on other elements within 
    // this div. But is not working!? For up when you click on the div 
    // or span element inside the div # click it also performs the function, 
    // it is only if clicked on div # click and not on other elements 
    // within it.

    // and performs other functions that I will put
});

HTML:

<div id="click" thesame="1">

    <!-- Clicks and does not perform function Click() -->
    <span> Title HI! </span>   

    <!-- Clicks and does not perform function Click() -->
    <div id="show_modal"> Show Modal Window </div>

</div>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

使用event.target 来识别点击了哪个元素。像这样的东西应该可以解决问题

$("#click").on("click", function(e){ 
    if (e.target.id != "click" ) return false;
    ....
};

请注意,您需要将 e 作为事件处理程序的参数传递

DEMO

如果您需要将想法推广到页面中的任何 div,您应该这样做

$("div").on("click", function(e){ 
    if (e.target.nodeName == "DIV") return false;
    ....
};

【讨论】:

  • 朋友,但是如果我不使用 #click 只使用 $ ("div.") On ("click", ... 来验证用户是否点击了同一个 div而不是里面的其他标签?应该是:$ ("div".) Live ("click", function (e) { if (e! = "click") return false; ?
  • @user2632011:你会使用event.target.nodeName == "DIV"
  • @user2632011 你也可以查看event.target != this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 2017-12-04
  • 2023-03-23
相关资源
最近更新 更多