2015-04-28 47 views
4

现在,一些replaceWith代码正在工作,另一个不是。例如,此代码的工作:如何使用replaceWith替换多个div类中的img和div ID的

$('.maincontent>h1:contains("Oakland Raiders")').replaceWith('<img src="http://i.nflcdn.com/static/site/6.3/img/subheaders/oak.png" class="subheader" />'); 

下面是从网站上关于如果使用在Firefox中检查元素这个特定部分的一些HTML代码:

<div class="maincontent"> 

    <img class="subheader" src="http://i.nflcdn.com/static/site/6.3/img/subheaders/stl.png"></img> 
    <div id="team_wrapper"> 
     <div id="team-overview-wrapper"> 
      <div id="team-overview-profile"> 
       <div id="team-overlay-container"> 
        <img class="team-overlay" src="/img/m25/right/339.png"></img> 
       </div> 
       <div class="team-bio"> 
        <div class="team-logo"> 
         <div class="teamimage-left" style="background-image: url("/img/m25/left/339.png");"></div> 
        </div> 

注意:你所不能看到的是h1元素,但您可以看到如果您查看页面源而不是检查元素。

H1的部分你不能看到在检查元素,但可以看到,如果你看一下页面的源代码,它看起来像这样:

<div class="maincontent"> 

    <h1>Oakland Raiders</h1> 
         <div id="team_wrapper"> 
         <div id="team-overview-wrapper"> 
         <div id="team-overview-profile"> 
            <div id="team-overlay-container"> 
                    <img class="team-overlay" src="/img/m25/right/22.png"> 
                    </div> 
            <div class="team-bio"> 
             <div class="team-logo"> 
                      <div class="teamimage-left" style="background-image: url(&quot;/img/m25/left/22.png&quot;);"></div> 
                      </div> 
               <div class="team-info"> 

我不能让工作正在取代团队覆盖图像或团队徽标图像。我尝试了以下方法,它什么都不做。

$('.maincontent>h1:contains("Oakland Raiders")').replaceWith('<img src="http://www.papermag.com/uploaded_images/cclinemustard-funny.png" class="team-overlay" />'); 

$('.maincontent>h1:contains("Oakland Raiders")').replaceWith('<img src="http://www.papermag.com/uploaded_images/cclinemustard-funny.png" class="teamimage-left" />'); 

我怎能取代teamimage左图像,并使用replaceWith团队,覆盖图像?我不知道为什么在顶端的代码工作,但这一个没有。

+0

'h1'元素在哪里?正如我所想,它被替换为'img.subheader'。我错了吗? –

+0

你可以分享你的代码,包括'h1'元素......最可能的失败原因是一个糟糕的选择器(即元素不存在)。 'replaceWith'方法应该可以正常工作:http://jsfiddle.net/vbw910qo/ – Fenton

+0

@RadonirinaMaminiaina ive添加了h1元素。您只能在查看页面源 – user3556644

回答

1

replaceWith方法应该做你想做的事。

您提到检查元素查看源代码 HTML之间存在差异。很可能,“原始”HTML(通过查看源文件可见)由网站正在使用的其他脚本之一修改。换句话说,当你的JavaScript被触发时,H1元素可能真的不再存在。


编辑:

查看源 HTML确实包括脚本NEER底部...

<script type="text/javascript" src="https://googledrive.com/host/0B7MXCCVKUtiefmxvbFpMU0R6X2xIRHpPeWFHYV9vSmw3dVJIWndyUGJWSUlpX1c3THhHRUE/all42815.js"></script> 

...的与图像横幅取代了H1标题:

$('.maincontent>h1:contains("Oakland Raiders")').replaceWith('<img src="http://i.nflcdn.com/static/site/6.3/img/subheaders/oak.png" class="subheader" />'); 

您应该找到另一种方法来识别t他的团队(基于检查元素 HTML),或者确保您的脚本是先运行的。

+0

@ user3556644我想我找到了冲突的JS。更新我的答案以包含它。 –

+0

这实际上是我正在使用的脚本。我试图添加代码来替换我提到的其他图像。 – user3556644

+1

@ user3556644然后我认为这是你的脚本有冲突。 :-)事情是,你的代码用图像替换H1。然后,当你想再次使用H1作为参考点时,它不再存在。 –