使用Javascript选择div导致页面未找到错误

我设法获得了另一个线程的帮助,用于使用JavaScript 更改元素的标题和链接( 使用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 = "Click Here"; 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 = "Click Here"; 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 = "Click Here"; jQuery('#c27-single-listing > section > div.profile-cover-content.reveal.reveal_visible > div > div > ul > li:nth-child(3) > div').replaceWith(link2); 

附件是指向我定位的HTML代码( 链接 )的链接 。 请注意,该链接仅反映与我无法工作的javascript代码相关的html,即。 href2 。 我没有发布href所针对的细分,因为它可能会变得太乱。 我的目的是用“ Click Here替换www.hotmail.com ,但是用户应该能够选择“ 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( `Click Here` ); }); }, 2000); }); 
         

使用:eq()选择器选择第4个li ,然后替换其内容:

HTML:

  
https://www.hotmail.com

JQuery的:

 var href2 = $('.container li:eq(3) > .buttons').html(); var link2 = "Click Here"; $('.container li:eq(3) > .buttons').replaceWith(link2); 

在这里工作演示