繁体   English   中英

更改div中的所有Anchor href链接

[英]Change all Anchor href link inside a div

我正在尝试使用jQuery更改所有html锚href链接,但无法正常工作。 当我单击按钮时,它选择第一个链接并在所有位置替换。

 var link = $('#content a[href]'); $("button").click(function() { var lin = $("#content a").attr('href'); var rep = "http://example.com/?redirect="; $("#content a[href]").attr("href", rep + "" + $("#content a").attr('href')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> <a href="http://google.com">Google</a> <a href="http://fb.com">Facebook</a> </div> <button>Click</button> <div class="p"></div> 

您正在使用$("#content a").attr('href')替换href ...它将找到第一个匹配项并替换为所有

您必须使用each()查找所有链接,然后使用$(this).attr('href')进行区分

堆栈片段

 $(document).ready(function() { $("button").click(function() { var rep = "http://example.com/?redirect="; $("#content a[href]").each(function() { $(this).attr("href", rep + "" + $(this).attr('href')); }) }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> <a href="http://google.com">Google</a> <a href="http://fb.com">Facebook</a> </div> <button>Click</button> <div class="p"></div> 

暂无
暂无

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

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