繁体   English   中英

使用Javascript替换HTML中的href文本

[英]replace href text in HTML using Javascript

是否可以使用Javascript将以下代码中的href值从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>

由于您需要它专门针对这个确切的链接,只需:

 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> 

哎呀,似乎所有其他答案都很复杂。

这很简单:

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

或者,如果你不知道在哪里放置它/如何包含它,那么:

<head></head>标记之间添加以下内容:

<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>
<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM