单击jquery中的当前div不起作用

时间:2013-07-29 23:37:23

标签: javascript jquery

帮助,解决方案:

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>

1 个答案:

答案 0 :(得分: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;
    ....
};