【问题标题】:A selector switch id with jquery as condition以 jquery 为条件的选择器开关 id
【发布时间】:2016-05-18 19:43:24
【问题描述】:

也许我的要求太简单了,也许不是。无论如何,当链接被按下时,我需要调用页面的某个锚点,它会输入一个特定的 URL,并带有一个特定的锚点向下滚动到该锚点。

我是这样用 jquery 做的:

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);

    if(anchor!="") {

        var newAnchor= "'#anchor-" +anchor+"'";

        $(newAnchor).trigger("click");

    }

});     

我认为这是不可能的,我当然没见过,我得到以下错误:

Uncaught Error: Syntax error, unrecognized expression: '#anchor-2015'

是否可以像这样动态调用选择器?还有其他方法吗?

谢谢。

【问题讨论】:

  • window.location.hash = "anchor-" +ancla;

标签: javascript jquery hash anchor


【解决方案1】:

去掉单引号,它们不是必需的。

var newAnchor= "#ancla-" + anchor;

【讨论】:

  • 太棒了!!我花了几个小时浏览但没有成功。惊人的。 :D
【解决方案2】:

是的,这是可能的。你有错误的引号。

$(document).ready(function() {

    var anchor = window.location.hash.substring(1);


if(anchor!=""){

    var newAnchor= "#anchor-" + anchor;

    $(newAnchor).trigger("click");


    }


}); 

【讨论】:

  • 太好了,太好了。有时它们是如此简单却又如此复杂的错误。解决方案摆在我面前,我看不到。 : D
  • # 之前还有多余的引号。
猜你喜欢
  • 2010-10-11
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
相关资源
最近更新 更多