Javascript jQuery:如果此 HREF 包含

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6374682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:28:10  来源:igfitidea点击:

jQuery: If this HREF contains

javascriptjquery

提问by curly_brackets

Why can't I get this to work??

为什么我不能让它工作?

$("a").each(function() {
    if ($(this[href$="?"]).length()) {
        alert("Contains questionmark");
    }
});

Ps.: This is just at simplifyed example, to make it easier for you to get an overview.

Ps.:这只是一个简化的例子,让你更容易获得一个概览。

回答by Matt Ball

You could just outright select the elements of interest.

您可以直接选择感兴趣的元素。

$('a[href*="?"]').each(function() {
    alert('Contains question mark');
});

http://jsfiddle.net/mattball/TzUN3/

http://jsfiddle.net/mattball/TzUN3/

Note that you were using the attribute-ends-withselector, the above code uses the attribute-containsselector, which is what it sounds like you're actually aiming for.

请注意,您使用的是attribute-ends-withselector,上面的代码使用了attribute-containsselector,这听起来像是您的实际目标。

回答by Christopher Armstrong

$("a").each(function() {
    if (this.href.indexOf('?') != -1) {
        alert("Contains questionmark");
    }
});

回答by Pointy

It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.

它不起作用,因为它在语法上是荒谬的。你根本无法在 JavaScript 中那样做。

You can, however, use jQuery:

但是,您可以使用 jQuery:

  if ($(this).is('[href$=?]'))

You can also just look at the "href" value:

您也可以只查看“href”值:

  if (/\?$/.test(this.href))

回答by Amir Ismail

use this

用这个

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

回答by Ender

Along with the points made by others, the $=selector is the "ends with" selector. You will want the *=(contains) selector, like so:

与其他人提出的观点一起,$=选择器是“结尾的选择器。您将需要*=( contains) 选择器,如下所示:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

这是一个现场演示 ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

正如 Matt Ball 所指出的那样,除非您还需要在没有问号的情况下操作链接(可能是这种情况,因为您说您的示例已简化),否则只需选择您想要的链接,代码会更少,速度也会更快首先:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

回答by Tim S. Van Haren

Try this:

尝试这个:

$("a").each(function() {
    if ($('[href$="?"]', this).length()) {
        alert("Contains questionmark");
    }
});