[英]fetch value img src jquery
通過以下結構獲取img src值的正確方法是什么? 下面的代碼返回空。
JS bin(單擊笑臉): https : //jsbin.com/lelaxam/edit? html,js,output
注意:當我移除圖像周圍的A HREF標簽時,我會收到圖像src,如果我在IMG周圍放置A HREF標簽,則不會收到IMG SRC
HTML:
<td class="sim-row-edit" data-type="testtest" style="padding-right:10px">
<a href="http://crezzur.com" target="_blank">
<img src="https://img.smileys.nl/152/winky.png" alt="" border="0" width="42" height="42" />
</a>
</td>
JQUERY:
if (big_parent.attr("data-type") == 'testtest') {
$("#sim-edit-testtest .image").val(big_parent.children('img').attr("src"));
$("#sim-edit-testtest .url").val(big_parent.children('a').attr("href"));
您應該使用jQuery.data
來獲取data-
屬性的值,而不是jQuery.attr
。
成功選擇圖像后,就可以像上面一樣使用.attr('src')
。
但是,您的代碼中有問題,您試圖錯誤地獲取圖像。 您的HTML代碼顯示:
<img id="sim-edit-testtest .image" src="https://img.smileys.nl/152/winky.png" alt="" border="0" width="42" height="42" />
因此$('#sim-edit-testtest .image').find('img')
遠遠超出了$('#sim-edit-testtest .image').find('img')
。 選擇器中的#sim-edit-testtest
.image
和.image
之間不應有空格,因為它不是子元素, 是具有類和 id的一個元素,也沒有子元素img
元素,它已經是 img
元素。 請嘗試以下代碼。
if ( big_parent.data('type') == 'testtest' ) {
$('#sim-edit-testtest.image').attr('src');
}
.image
說,選擇器中.image
也是一個小問題,因為ID在頁面中應該已經是唯一的,因此可以進一步簡化為:
if ( big_parent.data('type') == 'testtest' ) {
$('#sim-edit-testtest').attr('src');
}
您必須像這樣使用它:
$('#sim-edit-testtest img').attr('src');
此代碼捕獲並顯示IMG SRC和HREF,如您在本示例中看到的那樣: https ://jsbin.com/lelaxam/edit?html,js,output
唯一的問題是,如果找到它,它會抓住第一個img src,我該如何選擇按下的img src?
$("#sim-edit-testtest .image").val($('img', 'a').attr("src"));
$("#sim-edit-testtest .url").val(big_parent.children('a').attr("href"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.