使用Javascript替换HTML中的href文本

3

是否可以使用 Javascript 来将以下代码中的 href="http://**store**.mystitexxx.co.nz" 更改为 href="http://**www**.mystitexxx.co.nz"?它需要特定于此 DIV 或图像,即不是全局的。

<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

我怀疑你没有完整地提出问题。你是想让它始终替换为完全相同的URL吗?还是你想“检测”一下URL中是否已经有了“www”,如果没有,就添加“www”? - random_user_name
我总是想用确切的 URL 替换它,但仅适用于徽标图像,而不是页面上的其他位置。 - David Rook
3个回答

3

既然您需要具体到此链接,只需:

document.getElementById("link").href = "http://www.mystitexxx.co.nz";
<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store" id="link"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>

使用jQuery:

$("#link").attr("href", "http://www.mystitexxx.co.nz"); 

编辑:如果您无法控制HTML以添加ID。 (如果您可以的话,为什么要使用Javascript更改href呢?:P)

document.querySelector("h1.logo a").href = "http://www.mystorexxx.co.nz";
//$("h1.logo a").attr("href", "http://www.mystitexxx.co.nz"); 
<div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>


谢谢,但不幸的是img没有ID,我不能直接添加一个,有没有办法先使用Javascript添加它? - David Rook
我以为这是你的代码,我会在不使用ID的情况下进行编辑。 - Marcos Casagrande
2
需要考虑的一件事是,您正在处理的HTML是否与您向我们展示的示例完全匹配。如果您有其他锚点,则必须修改代码以处理它们。您想要替换的链接必须通过ID或其在标记中的位置唯一识别。如果您需要更改多个链接,则代码将完全不同。 - StevenDStanton

2

哎呀,看起来其他答案都很复杂。

其实很简单:

jQuery('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');

或者,如果您不知道将这个放在哪里/如何包含它,那么:
在您的 和 标签之间,添加以下内容:
<script>
    jQuery(function($) {
        $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
    }); 
</script>

如果您尚未加载jQuery,只需像这样添加(同样位于<head>标签之间):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
    jQuery(function($) {
        $('h1.logo a').attr('href', 'http://www.mystitexxx.co.nz');
    }); 
</script>

0
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<style type="text/css">
    .selected{
        background-color : green;
    }
    </style>
<script>

    $(document).ready(function () {

        $('.logo a img.img-responsive').attr('src', "http://www.mystitexxx.co.nz")

    });
</script>
</head>
<body>
    <div id="ctl00" class="hidden-xs">
   <h1 class="logo clearfix">
      <a href="http://store.mystorexxx.co.nz" title="My Store"><img class="img-responsive"src="/user/files/logo.png?t=1601271313" title="My Store" alt="My Store"/></a>
   </h1>
</div>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接