开发者

jQuery attr method failing to add attribute

In certain conditions I want to open links in the same window, while in others I want to open them in a new window. I have the following jQuery code:

if (internal) {
    jQuery(".main a").removeAttr('target');
} else {
    jQuery(".main a").attr('target', '_blank');
}

I have two 开发者_运维知识库<a>s contained in the "main" div. One is directly under the div while the other is buried under a couple of sub-divs. When it runs, it only adds the blank target to the first <a> tag. However, when I set a breakpoint through Firebug and step through it, everything works fine. Is there a reason it wouldn't work at full speed? What's the workaround?


Is the particular code executed during the onload event? In jQuery you normally use $(document).ready() for this. E.g.

$(document).ready(function() {
    // Do stuff onload.
});

Otherwise it would be executed immediately while the HTML DOM tree is still not fully built up and initialized yet.


Try using each() to step through the A elements:

jQuery(".main a").each(function() {
  $(this).attr('target', '_blank');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜