jQuery attr()不支持'replace'属性或方法

jQuery attr() doesn't support property or method 'replace'

本文关键字:属性 方法 replace attr 不支持 jQuery      更新时间:2023-09-26

我有以下脚本,在chrome/Firefox中工作良好,但在IE中不工作。

对象不支持"replace"属性或方法

我需要替换url的一部分,并在新选项卡中打开该链接。基本上它是运行在一个安全的网站和所有外部链接得到服务器名称前面,所以我需要替换为'http:'

$('a[href*="youtube.com"]').attr("href", $('a[href*="youtube.com"]').replace ("https://serverdomain.com/", "http:"))

首先,您试图在jQuery对象上使用replace,因此您得到replace is undefined错误。其次,attr()可以采用一个函数,您可以使用该函数更简单地返回替换值。试试这个:

$('a[href*="youtube.com"]').attr("href", function(i, value) {
    return value.replace("https://serverdomain.com/", "http:");
});

我想您还需要将http:更改为http://,以确保您的url仍然有效。