最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery this.href String Comparison Not Working - Stack Overflow

programmeradmin4浏览0评论

I have a simple jQuery script that I'm trying to build upon but I can't get the href string parison to return true:

<a class="test" href="/Services/Cloud-Hosting">Click Me</a>​

My script is as follows:

$('.test').click(function() {
if ($(this).href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
});​

I keep getting the alert of 'no' even thought the hrefs are the same. What am I missing?

I have a simple jQuery script that I'm trying to build upon but I can't get the href string parison to return true:

<a class="test" href="/Services/Cloud-Hosting">Click Me</a>​

My script is as follows:

$('.test').click(function() {
if ($(this).href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
});​

I keep getting the alert of 'no' even thought the hrefs are the same. What am I missing?

Share Improve this question asked Jul 2, 2012 at 18:13 Kyle SussKyle Suss 4553 gold badges9 silver badges18 bronze badges 1
  • Now after you got your answer, check this to know the explanation stackoverflow./questions/3722544/… – Adi Commented Jul 2, 2012 at 18:17
Add a ment  | 

4 Answers 4

Reset to default 8

Change:

if ($(this).href

To:

if (this.href

Or $(this).attr('href') but former is better.

To read attributes, you need to use attr (shorthand for attribute)

This is what you should have:

if (this.href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}

try this:

if ($(this).attr('href') == "/Services/Cloud-Hosting") {

jQuery objects don't have an href property. Just access the property of the HTMLAnchorElement using this.href instead of creating a new jQuery object with $(this).

See .attr() and try this:

$(this).attr('href') == "/Services/Cloud-Hosting"

instead

发布评论

评论列表(0)

  1. 暂无评论