在我的页面中,我有如下所示的元素
<div id="target" class="textarea">
HTML is written in the form of HTML elements consisting of tags enclosed in angle
brackets (like
<html>
),within the web page content. HTML tags most commonly come in pairs like and ,although
some tags, known as empty elements, are unpaired, for example
<img>. The purpose of a web browser is to read HTML documents and compose them into
visible or audible web pages. The browser does not display the HTML tags, but uses
the tags to interpret the content of the page.
<div id="target2" class="textarea"><div id="test3"><div id="test4">Right Click Here</div> </div>
</div>
</div>
每当我单击 Div 元素 target2
或 test2 时,我需要检查我拥有的元素
或 ("target2")
是否是同一个元素test3
。这里 test2
和 test3
或包含在 target2
中。我当前正在使用 $(e).is($.trim(my element) )
检查我拥有的元素是否与我单击的元素相同。但是,每当我单击 div 元素时,e.target
都会返回 test4
target2
。但是,我实际上点击了target2
。我该怎么做?
提前致谢。
最佳答案
您可以使用closest()
来测试一个元素是否在另一个元素内
$('div').click(function (e) {
e.stopPropagation();
if ($(e.target).closest('#target2').length) {
alert('I am within target2, or I am target2');
}
});
所讨论的预期行为非常不清楚。如果这不是您想要的,请提供更多详细信息
关于javascript - 检查提供的元素是否在单击的目标内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29049001/