防止点击改变URL时的href =#?

时间:2016-05-29 21:47:16

标签: jquery html

我有一个跳转到页面特定部分的链接。

 <a href="#secondPage/2" class="projectLink">Project Infomation</a>

点击网址更改为 website.com/project.html#secondPage/2

我正在尝试阻止将#secondPage / 2 添加到网址。

我正在使用的当前脚本无效。

 <script>
    $('#secondPage/2').click(function(event
    ){
        even.preventDefault();
    });
  </script>

我哪里错了?

2 个答案:

答案 0 :(得分:4)

您没有使用正确的jQuery选择器来实现此功能。 您可以尝试使用

$('a[href=#secondPage/2]').on('click',function(event){
    event.preventDefault();
});

OR

$('a.projectLink').on('click',function(event){
    event.preventDefault();
});

或者您可以在链接中添加ID并将其用作jQuery对象中的选择器。在这种情况下,您的 HTML 将是这样的......

<a href="#secondPage/2" id="secondPage-2" class="projectLink">Project Infomation</a>

您的 jQuery / Javascript 将是

$('a#secondPage-2').on('click',function(event){
    event.preventDefault();
});

答案 1 :(得分:0)

您需要转义/使用双反斜杠以及更正属性选择器。

#include <iostream>
using namespace std;

class Enemy {
    protected: 
        int attackPower;
    public:
        void setAttackPower(int a){
            attackPower = a;
        }
};

class Ninja: public Enemy {
    public:
        void attack() {
            cout << "Ninja! - "<<attackPower<<endl;
        }
};

class Monster: public Enemy {
    public:
        void attack() {
            cout << "Monster! - "<<attackPower<<endl;
        }
};

int main() {
    Ninja n;
    Monster m;
    Enemy *e1 = &n;
    Enemy *e2 = &m;

    e1->setAttackPower(20);
    e2->setAttackPower(80);

    n.attack();
    m.attack();
}
  

使用任何元字符(例如!&#34;#$%&amp;&#39;()* +,。/:;&lt; =&gt;?@ [] ^`{| }〜)作为名称的文字部分,必须使用两个反斜杠进行转义:\。例如,id =&#34; foo.bar&#34;的元素可以使用选择器$(&#34; #foo \\。bar&#34;)。

https://api.jquery.com/category/selectors/