Jquery $this 或each() 一次指定一个链接
我发现 jQuery 很难学,因为似乎有很多方法可以编写同样的东西。
作为练习,我想将锚标记中的文本填充到 links href 属性中。
例如,
<a href="">http://www.something.com</a>
成为
<a href="http://www.something.com">http://www.something.com</a>
我的第一次尝试
<script type="text/javascript">
$(document).ready(function() {
var text = $('a').text();
$('a').attr( 'href', text );
});
</script>
显然是行不通的,因为我需要指定为每个链接执行此操作。
我应该使用 foreach 循环吗? .each() 函数?或者$这个符号? 他们都会工作吗?
Im finding jQuery to difficult to learn as there seems to be many ways to write the same thing.
As an exercise I would like to take the text within anchor tags and stuff it into the links href attribute.
eg
<a href="">http://www.something.com</a>
to become
<a href="http://www.something.com">http://www.something.com</a>
my first attemp was
<script type="text/javascript">
$(document).ready(function() {
var text = $('a').text();
$('a').attr( 'href', text );
});
</script>
which clearly doesnt work as I need to specify to do this action for each link.
Should I use a foreach loop? A .each() function? Or $this notation?
Would they all work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将返回每个锚节点文本值的组合。我刚刚在 stackoverflow 上做了它,它给了我:
,您应该使用 jQuery.prototype.each,这样您就可以保存对每个单独锚点文本的引用:
额外的好处是每个函数都在其自己的执行上下文中运行,您定义的每个变量、声明的每个“文本”都是唯一的该函数体,因此 .each 内部有更多的控制。
关于普通循环处理 - 我会在它上面使用 jQuery.prototype.each 因为它是一个更高级别的函数,你必须分配一个变量到nodeList的长度并从0开始,在长度处停止(或者如果顺序无关紧要,则执行相反的while循环)..这只会导致不必要的工作。
would return the combination of every anchor nodes text value.. I just did it on stackoverflow and it gave me:
Therefore you should use jQuery.prototype.each so you can save a reference to each individual anchor's text:
The added benefit is that each function runs in its own execution context, each variable you define, every 'text' declared is unique to that function body so there's a lot more control inside of a .each.
Regarding the vanilla loop deal - I would use jQuery.prototype.each over it because it's a higher level function, you would have to assign a variable to the length of the nodeList and start at 0, stop at the length ( or if order doesn't matter do a reverse while loop ).. this just causes more work than necessary.