jquery .each() 循环
我想阅读“.vm-video-title”-div 中的所有链接,并将它们分别发布在同一个 div 中。所以我制作了这个脚本:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
但我有一个问题,它读取所有 div 的所有链接并将它们放在一个 div 中。
示例:
<div class="vm-video-title"><a href="...">Text1</a></div>
<div class="vm-video-title"><a href="...">Text2</a></div>
<div class="vm-video-title"><a href="...">Text3</a></div>
输出:
<a href="...">Text1</a>Text1Text2Text3
<a href="...">Text2</a>Text1Text2Text3
<a href="...">Text3</a>Text1Text2Text3
想要的输出:
<a href="...">Text1</a>Text1
<a href="...">Text2</a>Text2
<a href="...">Text3</a>Text3
i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title"><a href="...">Text1</a></div>
<div class="vm-video-title"><a href="...">Text2</a></div>
<div class="vm-video-title"><a href="...">Text3</a></div>
output:
<a href="...">Text1</a>Text1Text2Text3
<a href="...">Text2</a>Text1Text2Text3
<a href="...">Text3</a>Text1Text2Text3
wanted output:
<a href="...">Text1</a>Text1
<a href="...">Text2</a>Text2
<a href="...">Text3</a>Text3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以直接选择
元素,并使用
after( )
[docs] 方法将每个内容分别附加到每个内容之后。这不会对现有元素进行“销毁然后重新创建”,例如
html()
[docs] 方法将。工作示例: http://jsfiddle.net/CCr9C/
You can select the
<a>
elements directly, and use theafter()
[docs] method to append the content of each after each one respectively.This doesn't do a "destroy then recreate" of the existing elements like the
html()
[docs] method will.Working example: http://jsfiddle.net/CCr9C/
这应该可以为您完成工作,
您需要在循环(el)中找到当前元素内的 div。
在您的代码中,您将在 div 中添加所有匹配“a”标签的 text() (即 Text1Text2Text3)
This should do the job for you,
you need to find the div inside current element in the loop (el).
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
你就快到了。而不是:
$("div.vm-video-title").text()
,它为您提供任何具有vm-video- 类的
,您需要在当前div
内的文本titlediv
内找到a
标签并从中获取文本。我们将this
作为context
传递,用于在当前div
中选择a
jQuery( 选择器, [上下文])
You were almost there. Instead of :
$("div.vm-video-title").text()
, which gives you text inside anydiv
with classvm-video-title
, you need to finda
tag inside currentdiv
and get text from it. We passthis
ascontext
for selectinga
inside currentdiv
jQuery( selector, [context] )