2017-01-30 102 views
1

我的頁面上有iFrame(id = iframe1)內部的img標籤。 他們中的一些已經src屬性設置爲myimg.jpg, 'myimg_small.jpg',myimg_large.jpg通過屬性的部分值查找元素

我想在裏面找#iframe1一切與srcmyimg,所以我寫了

images = $('#iframe1').contents().find('[src*="myimg"]') 

但我得到如下錯誤

Uncaught Error: Syntax error, unrecognized expression: [src*="myimg"])

at Function.Sizzle.error (jquery-1.8.2.js:4679)
at tokenize (jquery-1.8.2.js:4739)
at select (jquery-1.8.2.js:5099)
at select (jquery-1.8.2.js:5276)
at Function.Sizzle [as find] (jquery-1.8.2.js:3941)
at init.find (jquery-1.8.2.js:5372)
at <anonymous>:1:36

這裏有什麼問題?

更新

alert($('#if').contents().find('[src*="ss"]').next().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<iframe id='if'> 
 
    <img src='sss.jpg' /> 
 
    <div> 
 
    scdscd 
 
    </div> 
 
</iframe>

+0

你可以創建一個我們可以調試的示例嗎? – Rajesh

+5

你在那裏有一個額外的右括號。 – Enfyve

+1

您的JSFiddle代碼無效HTML - iFrame代碼內部的代碼不會奇蹟般地變成iFrame內容 - 我在這裏將代碼添加爲一個''''''代碼段。請閱讀https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe – mplungjan

回答

0

簡單地做:

var x = $("img[src$='myimg.jpg']"); 
alert(x.attr("src")); 
+0

它不會工作,因爲img在iframe內 – Imad

0

您對使用iframe錯了。 iframe必須使用src屬性並使用它來加載其他頁面的內容。 iframe不需要將其子元素直接包含在其標籤中。

你可以試試這個。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<iframe id='if' src="1.html"> 
</iframe> 


//1.html 
... 
    <img src='sss.jpg' /> 
    <div> 
    scdscd 
    </div> 

你可以嘗試如下。

alert($('#iframe1').contents().find('[src*="ss"]').next().html()); 
+0

這只是創建一個樣本,正如我所說的。 – Imad

+1

@Imad,我的意思是,你需要使用一個iframe來加載另一個頁面的內容。向這樣的iframe標籤添加子標籤是無用的,看起來像是一種濫用。 –

0

選擇器正常工作。你可以看到工作jsbin here

iframe的錯誤使用會對您造成問題。

如果要將內容添加到iframe,則必須使用src屬性或HTML字符串使用srcdoc屬性指定URL。

The srcdoc attribute specifies the HTML content of the page to show in the inline frame.

參考iframe srdoc

0

確保您的iframe src的目標是相同的網域主頁。否則,您不能訪問iframe內容。這被稱爲XSS(Cross Site Scripting),它被主流瀏覽器阻止。

如果您的iframe源在同一個域上,但仍然無法訪問它的內容,請確保設置一個setTimeout等待iframe內容被加載,因爲iframe內容在主頁加載後開始加載。