Error in javascript OR jquery select element [closed]

只愿长相守 提交于 2019-12-13 09:27:44

问题


Jquery:

$("#div td").live("click", function(){

alert("Hellow");

});

Javascript:

function alertH(){

alert("Hellow");

}

HTML Jquery:

<div>

<td>

<a>X</a>

<span> HI! </span>

</td>

</div>

Click on td and runs the jQuery function, but only if you click on td and not other tags inside, as in jquery?

HTML javascript:

<div>

<td onClick="alertH()">

<span> Hummm </span>

<a> Delete </a>

</td>
</div>

How do in javascript, and it only runs if you click directly on td and not in other html tags inside

Performs this function only if you click the div function and not in other tags inside the div. How do the two methods above?


回答1:


One way to do it is by adding the code on each element you dont want to call a function

onClick="event.cancelBubble = true;"

Another way is to check in the callback called to see the Target there.

<div onClick="test()" id="run">
Click Works<br>
<label>Not Work</label>
</div>

function test(){
    if (event.target.id !== "run") return false;
    alert(event.target);
}


来源:https://stackoverflow.com/questions/17935233/error-in-javascript-or-jquery-select-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!