[英]javascript equivalent of jquery all children selector
I have the following jquery selector which I am trying to convert to regular javascript. 我有以下jquery选择器,我正尝试将其转换为常规javascript。
$("#lelement>*").on("dblclick", function(){
});
what would the equivalent be with regular javascript ? 普通javascript相当于什么? Can I do this ?
我可以这样做吗?
document.getElementById('element').childNodes.addEventListener("dblclick", function(e){
});
You'll have to explicitly iterate over all elements which match the #lelement>*
selector (the collection can be obtained with querySelectorAll
), and then attach a handler to each of them: 您必须显式遍历所有与
#lelement>*
选择器匹配的元素(可以通过querySelectorAll
获得集合),然后将处理程序附加到每个元素:
document.querySelectorAll('#lelement > *').forEach((child) => { child.addEventListener('dblclick', () => console.log('double clicked!')); });
<div id="lelement"> <div>content 1</div> <div>content 2</div> </div>
Note that NodeList.forEach
isn't all that old a method; 请注意,
NodeList.forEach
并不是一个古老的方法。 not all browsers support it. 并非所有浏览器都支持它。 So, for ancient browsers, use a polyfill or
Array.prototype.forEach
instead: 因此,对于古老的浏览器,请改用polyfill或
Array.prototype.forEach
:
Array.prototype.forEach.call( document.querySelectorAll('#lelement > *'), (child) => { child.addEventListener('dblclick', () => console.log('double clicked!')); } );
<div id="lelement"> <div>content 1</div> <div>content 2</div> </div>
It would be the exact same selector, just passed to document.querySelectorAll()
. 这将是完全相同的选择器,只是传递给
document.querySelectorAll()
。
document.querySelectorAll("#element > *");
Then, you would enumerate the found nodes and manually set each up with an event handler. 然后,您将枚举找到的节点,并使用事件处理程序手动设置每个节点。 Since
.querySelectorAll()
returns a node list, it's best to convert that to an Array
so that the Array.forEach()
method can be reliably called in all browsers. 由于
.querySelectorAll()
返回节点列表,因此最好将其转换为Array
以便可以在所有浏览器中可靠地调用Array.forEach()
方法。
let elems = Array.prototype.slice.call(document.querySelectorAll("#element > *")); elems.forEach((el) => { el.addEventListener("dblclick", function(){ console.log("You clicked me!"); }); });
<div id="element"> <h1>Some Heading</h1> <p>Some Paragraph</p> <div>Some Div</div> </div>
One elegant, non-jQuery way to do this would be via querySelectorAll()
: 一种优雅的,非jQuery的方法是通过
querySelectorAll()
:
document.querySelectorAll('#lelement > *').forEach(function(node) { node.addEventListener("dblclick", function(e){ console.log('double clicked on child of #element'); }); })
p { margin:1rem; background:red; color:white; }
<div id="lelement"> <p>Double click me - Child 1</p> <p>Double click me - Child 2</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.