-1

目前,我使用 Javascript 替换与域相似的任何链接的一小部分(例如:othersite.com)我想知道如何在 JQUERY 中实现相同的效果。可能吗?我只想更改一小部分,而不影响链接的其余部分。因为我可以在 Jquery 中得到同样的结果(使用 Jquery)?我希望有人能帮忙,谢谢。

这是我的 Javascript 代码:

    函数更改文本(){
    var id = "乔希";
    var link = document.getElementsByTagName('a');
    var i = 链接长度;
    当我 - ){
        var lnk = 链接[i].href;
        如果(lnk.match(“othersite.com”)){
            链接[i].href = lnk.replace(/name=[^&]*/g, 'name='+id);
        }
    }  
}
更改文本();

..

<a href="http://www.othersite.com/?name=susan1&last=3">Text</a>
<a href="http://www.othersite.com/?name=PAtrIck01&lat=6">Text</a>
<a href="http://www.othersite.com/?name=1Smith&lat=49">Text</a>

使用Javascript效果,如下:

<a href="http://www.othersite.com/?name=JOSH&last=3">Text</a>
<a href="http://www.othersite.com/?name=JOSH&lat=6">Text</a>
<a href="http://www.othersite.com/?name=JOSH&lat=49">Text</a>

因为我可以在 Jquery 中得到同样的结果(使用 Jquery)?...... 谢谢你。

4

1 回答 1

1

正如其他人已经指出的那样,在 jQuery 代码库中使用“vanilla-js”并没有错。这种情况下的用例非常简单,您不应该遇到跨浏览器兼容性问题。

无论如何,下面的代码段应该与您发布的代码段相同。

function fixAnchorHrefForJosh ($a) {
  $a.attr("href",
    $a.attr("href").replace(/name=[^&]*/g, "name=JOSH"));
}

function fixAnchorsHref () {
  $("a")
    .filter(function (i, el) {
      return $(el).attr("href").match("othersite.com")
    })
    .each(function (i, el) {
      fixAnchorHrefForJosh($(el));
    });
}

// Register an handler
// that will be executed when the DOM is loaded.
$(document).ready(fixAnchorsHref);

您可以将$.fn.filter$.fn.each视为 , ... 的 jQuery 等价物Array#filterArray#forEach但不要让您上当,它们之间存在差异,例如。回调参数的顺序。

$.fn.attr用作元素属性的 getter/setter。这是 jQuery 中的常见模式,例如。$.fn.css, $.fn.height...

function fixAnchorHrefForJosh($a) {
  $a.attr("href",
    $a.attr("href").replace(/name=[^&]*/g, "name=JOSH"));
}

function fixAnchorsHref() {
  $("a")
    .filter(function(i, el) {
      return $(el).attr("href").match("othersite.com")
    })
    .each(function(i, el) {
      fixAnchorHrefForJosh($(el));
    });
}

// Register an handler
// that will be executed when the DOM is loaded.
$(document).ready(fixAnchorsHref);
a {
  display: block;
  margin-bottom: 10px;
}

a:after {
  content: attr(href);
  display: block;
}
<a href="http://www.othersite.com/?name=susan1&last=3">Text</a>
<a href="http://www.othersite.com/?name=PAtrIck01&lat=6">Text</a>
<a href="http://www.asite.com/?name=1Smith&lat=49">Text</a>
<a href="http://www.othersite.com/?name=1Smith&lat=49">Text</a>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

于 2013-05-01T13:16:58.783 回答