簡體   English   中英

如何修改src屬性的值 <img> 使用jquery或javascript標記

[英]how to modify the value of src attribute of <img> tag using jquery or javascript

我正在解析html字符串片段並更改圖像標簽的src屬性。 (即替換以“ ..”開頭的路徑

var hstr = $.parseHTML(str);
$(hstr).find('img').each(function(e){
var srcvalue = $(this).attr('src');
srcvalue = srcvalue.replace(/../gi, "");
$(this).attr('src', srcvalue);
});

然后通過附加結果來設置div元素的內容

document.getElementById('#section').append($(hstr));

但是它不起作用...誰能告訴我出了什么問題?

不要搞亂純JS DOM和Jquery。 使用$('#section').append($(hstr))

不要與Jquery (#ID)選擇器混淆 ,使用

$('#section').append($(hstr));

或( 不需要#並在DOM元素中使用appendChild

document.getElementById('section').appendChild($(hstr));

您應該追加操作對象,創建另一個對象,DOMElement對象也沒有append方法。

$(hstr).find('img').each(function(e){
    // ...
}).appendTo('#section');

使用prop方法:

$(hstr).find('img').prop('src', function(index, srcValue) {
    return srcValue.replace(/../g, "");
}).appendTo('#section');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM