DIV属于元素,你怎么知道

The DIV belongs to the element, how do you know?

本文关键字:你怎么知道 元素 属于 DIV      更新时间:2023-09-26

我有两个div,其中有一些元素(图像,文本等),我需要知道哪个div包含被单击的元素。例如:

  • 如果我点击div 1中的任何元素,然后重定向到"pagina1.php"
  • 如果我点击div 2中的任何元素,然后重定向到"pagina2.php"

如何在jquery中做到这一点?

只需将点击处理程序绑定到div的(您的内容包装器):

$( '#div1, #div2' ).click( function ( e ) {
    this // references the DIV inside which the click occured
    e.target // references the element that was clicked
});

你可以将click事件绑定到div中的所有元素,你可以在这里找到如何做到这一点http://api.jquery.com/click/,你可以为每个div做这样的事情:

$('div#1 > *').click(function(e) {
  //This will tell you the tagname of the element that was click.
  alert($(this).tagName);
  //this will redirect you to pagina1.php might not be the best choice
  window.location.replace('pagina1.php');
});

对div#2也要做同样的操作。

需要注意的是,我所做的选择器只适用于div元素的第一个子元素

Saludos .

$('div.element-1 > *').click(function() { alert('first div childs') });

我很确定$('').click适用于几乎所有的HTML元素(包括div)。这是因为事件通过元素的父链向上冒泡。比如:

<script>
$(document).ready(function()
{
$("#div1").click(function() { alert("something in div1 clicked"); }
$("#div2").click(function() { alert("something in div2 clicked"); }
$("#div3").click(function() { alert("something in div3 clicked"); }
}
</script>
</head>
<body>
<div id="div1"><table><tr><td><span>blah</span></td></tr></table><div>
<div id="div2"><span>blah2</span><div>
<div id="div3"><img src=""><div>