更有效地查找和提取数据的方法?
给定这个 HTML(我意识到 srcs 和 href 无效,这是伪代码):
<div id="featured-story">
<a href="fullstory">
<img src="thumbnail" />
</a>
<h2><a href="fullstory">Headline</a></h2>
</div>
我想提取各种数据。我这样做是这样的:
var $featStory = $('#featured-story');
var featHeadline = $featStory.children('h2').text();
var featURL = $featStory.children('h2').children('a').attr('href');
var featImg = $featStory.children('a').children('img').attr('src');
有没有更好、更有效的方法来做到这一点?所有对 .children() 的调用看起来都很笨重。 (我没有使用 .find() 因为 .find() 无限深,我只想要一层)
编辑:不,没有 ID 是我可以用作快捷方式的类,我也没有控制权覆盖正在生成的 HTML。
编辑2:嗯,忘记 $featStory var 并执行以下操作可能更有意义:
var featHeadline = $('#featured-story > h2').text();
var featURL = $('#featured-story > h2 > a').attr('href');
var featImg = $('#featured-story > a > img').attr('src');
Given this HTML (I realize the srcs & hrefs aren't valid, this is pseudo-code):
<div id="featured-story">
<a href="fullstory">
<img src="thumbnail" />
</a>
<h2><a href="fullstory">Headline</a></h2>
</div>
I want to pull various data out. I'm doing so like this:
var $featStory = $('#featured-story');
var featHeadline = $featStory.children('h2').text();
var featURL = $featStory.children('h2').children('a').attr('href');
var featImg = $featStory.children('a').children('img').attr('src');
Is there a better, more efficient way to do this? It just seems clunky with all the calls to .children(). (I didn't use .find() because .find() goes infinite levels deep, and I only wanted one level down)
EDIT: and no, there are no IDs are classes I could use as shortcuts, nor do I have control over the HTML being generated.
EDIT 2: hmm, might make more sense to just forget the $featStory var and do this:
var featHeadline = $('#featured-story > h2').text();
var featURL = $('#featured-story > h2 > a').attr('href');
var featImg = $('#featured-story > a > img').attr('src');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 Orbling 的答案类似,但是您实际上可以将上下文传递到选择器中并继续使用缓存的选择器,就像这样 -
这实际上应该比重新定义选择器更有效。
Similar to Orbling's answer however you can actually pass contexts into the selector and keep using your cached selectors like so -
That should actually be minimally more efficient than redefining your selector.
或者,为了提高效率,您可以保留捕获的
#featured-story
对象。Or, for efficiency, you can retain the captured
#featured-story
object.将一些元数据添加到标记中,以便可以轻松地将其序列化为 JSON 对象。
data- 属性对此非常有用,它们是任意命名的。
您可能正在查看这个并意识到它的代码比您开始时的代码更多......但它非常可扩展。您可以添加新的 HTML 元素,它们最终会出现在您的对象中,而无需更改您的 JavaScript。希望这能为您指明正确的方向。
Add some metadata to your markup so it can be easily serialized into a JSON object.
data- attributes are great for this, they are arbitrarily named.
You are probably looking at this and realizing that this has more code than what you started with.. but its very scalable. You can add in new HTML elements and they'll end up in your object w/o altering your JavaScript at all. Hopefully this points you in the right direction.