我设法在另一个线程上获得帮助,使用JavaScript(Issue with changing the title of a link using jQuery)更改元素的标题和链接。
我已经尝试将技术应用到我的网站上的另一个元素,但我遇到了错误Error 404: The page your are looking for cannot be found.
因此,虽然此代码是孤立的:
var href = jQuery('#_tab_1 > div > div > div:nth-child(3) > div > div.pf-body > ul > li:nth-last-child(1) > p.item-property').html();
var link = "<a href='"+href+"' target='_blank'>Click Here</a>";
jQuery('#_tab_1 > div > div > div:nth-child(3) > div > div.pf-body > ul > li:nth-last-child(1) > p.item-property').replaceWith(link);
以下代码导致上述错误。
var href = jQuery('#_tab_1 > div > div > div:nth-child(3) > div > div.pf-body > ul > li:nth-last-child(1) > p.item-property').html();
var link = "<a href='"+href+"' target='_blank'>Click Here</a>";
jQuery('#_tab_1 > div > div > div:nth-child(3) > div > div.pf-body > ul > li:nth-last-child(1) > p.item-property').replaceWith(link);
var href2 = jQuery('#c27-single-listing > section > div.profile-cover-content.reveal.reveal_visible > div > div > ul > li:nth-child(3) > div').html();
var link2 = "<a href='"+href2+"' target='_blank'>Click Here</a>";
jQuery('#c27-single-listing > section > div.profile-cover-content.reveal.reveal_visible > div > div > ul > li:nth-child(3) > div').replaceWith(link2);
附件是我定位的html代码的链接(Link)。请注意,该链接仅反映与我无法工作的javascript代码相关的html,即。 href2
。我没有发布href所针对的细分,因为它可能会变得太乱。我的目的是用www.hotmail.com
替换Click Here
,但用户应该能够选择Click Here
并将它们引导到www.hotmail.com
。另外,因为我只需要选择html的相关部分,所以你在链接中查看的选择器将与我上面的代码中所述的选择器不同。
谢谢您的帮助。
这是一个可以满足您的需求的片段。请注意,您可以使用类(对于多个元素)或id(对于单个元素)。
基本上,我使用了几个命令来做你想做的事情:
each()
- 应该为选择器找到的每个元素执行以下函数。 this
将引用DOM元素text()
- 返回该项目的文本(不带html)replaceWith()
- 将用你想要的任何东西取代元素在这个例子中,每个具有类should-become-link
的项目将在2秒后成为一个链接(因为setTimeout
)。元素内的原始文本将用作新的href
值。
$(document).ready(function() {
setTimeout(function() {
var element = $('.should-become-link');
element.each(function(index) {
var $this = $(this);
var currentText = $this.text();
$this.replaceWith(
`<a href="${currentText}" target="_blank">Click Here</a>`
);
});
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons medium button-outlined should-become-link">
https://www.hotmail.com
</div>
<div><a href="http://www.google.com" target="_blank">shouldn't change!</a></div>
<div><a href="//www.google.com" target="_blank">shouldn't change!</a></div>
<div><a href="//www.google.com" target="_blank">shouldn't change!</a></div>
<div><a href="//www.google.com" target="_blank">shouldn't change!</a></div>
<div><a href="//www.google.com" target="_blank">shouldn't change!</a></div>
<div class="buttons medium button-outlined should-become-link">
https://www.google.com
</div>
这是一个codepen
使用:eq()
选择器选择第4个li
,然后替换其内容:
HTML:
<div id="buttons medium button-outlined">https://www.hotmail.com</div>
JQuery的:
var href2 = $('.container li:eq(3) > .buttons').html();
var link2 = "<a href='"+href2+"' target='_blank'>Click Here</a>";
$('.container li:eq(3) > .buttons').replaceWith(link2);
工作演示here