如果我这样做
var domElement = $("#id");
Run Code Online (Sandbox Code Playgroud)
返回的元素是div标签,
我怎么能做类似的事情
domElement.$('div a:nth-child(3)').after(somehtml);
Run Code Online (Sandbox Code Playgroud)
这是一个示例,我想在"domElement"div下的第三个链接之后添加一些HTML.
以上似乎不起作用.我有很多例子,我已经从整个页面HTML中选择了某个元素,然后我想在该元素的"上下文"中工作.
在90%的情况下,我想继续jQuery选择,来自页面的先前选择的DOM元素的traversion和操作,而不是像$(..)这样的整个页面.
你想要.find():http://api.jquery.com/find/
var domElement = $("#id");
domElement.find('div a:nth-child(3)').after(somehtml);
Run Code Online (Sandbox Code Playgroud)
如果您计划与多个子选择此链接domElement,结束每个使用的.find()有.end():
$("#id")
.find('div')
.click(function() { alert("#id div"); })
.find('a.my-class1')
.click(function() { alert("#id div a.clickable"); })
.end() // stop working with 'a.my-class1'
.find('a.my-class2')
.click(function() { alert("#id div a.my-class2"); })
.end() // stop working with 'a.my-class2'
.end() // stop working with 'div'
.click(function() { alert("#id"); });
Run Code Online (Sandbox Code Playgroud)
从概念上讲,您使用.find()深入到DOM中,然后使用.end()升级DOM.从技术上讲,"降序"和"升序"是不正确的,因为你也可以首先向上遍历然后使用像.parent()或者这样的函数向下遍历.closest(),这两个函数都可以终止.end()以返回到原始选择器:
$("#id")
.parent()
.click(function() { alert("I'm #id's parent!"); })
.end()
.click(function() { alert ("back to #id"); });
Run Code Online (Sandbox Code Playgroud)