【问题标题】:jquery attr('href') not workingjquery attr('href')不起作用
【发布时间】:2012-08-16 22:28:43
【问题描述】:

更新,问题解决。问题在于我在尝试更改 HREF 后调用的函数,这实际上是在将其改回。


使用 jQuery,我试图根据 URL 中包含的哈希更改一系列链接的 HREF 属性,但该属性根本没有改变,它被更改为空字符串。

谁能看到我在这里做错了什么?为什么它不起作用?

http://fwy.pagodabox.com/categories/sculptures/#grid

有问题的链接是

全部 展览 安装 对象 印刷 雕塑

在二级导航中

function navHash($navlinks, hashtxt) {

        // loop through specified links
        $navlinks.each(function(){
            var $me = $j(this),
                myhref,
                index;

            // Does this link have an href… if not move on          
            if( typeof $me.attr('href') === "undefined" )
                return false;

            myhref = $me.attr('href');
        index = myhref.indexOf('#');

        // if my href doesn't have the specified hash text, add it, else remove it
        if(myhref.indexOf(hashtxt) === -1) {
            $me.attr("href", hashtxt);
        } else {
            $me.attr("href", myhref.substring(0, index));
        }   
    });
}




   $j(document).ready(function($){

        var $navlinks = $j('.sub-nav li:not(.views) a');

        if(window.location.hash == '#grid') {
            navHash($navlinks, '#grid');
            $('.views .ic-grid').click();
        }
// so on...

谢谢!!!

【问题讨论】:

  • 您能否解释得更好一些,或者用您看到此问题的最简单用例创建一个 jsfiddle?这对我来说可以。 jsfiddle.net/CxeTs
  • 你能创建一个jsfiddle.net 来展示你的问题吗?
  • 小提示:您可以通过在.each 回调中直接使用this.href 来避免.attr 的开销。

标签: jquery attr


【解决方案1】:

如果您在此处返回false,您将停止循环。

if(typeof $me.attr('href') === "undefined")
   return false;

返回true 继续循环。

【讨论】:

  • 我不认为那是真的......如果我在返回 false 之后放一个 alert() ,它会触发正确的 # 次
猜你喜欢
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 2011-09-26
  • 2012-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多