[英]How to get value of WYSIWYG and insert it in textarea Tag by Javascript only?
[英]Javascript (or jquery) to get every image tag of a textarea value
因此,假設我有一個textarea,其值為:
<p>..random content..</p>
<img src="myimage1.jpg" />
<p>..random content..</p>
<img src="myimage2.png" />
<p>..random content..</p>
我想檢查每個img標簽的出現情況並將src存儲在數組中。 像這樣:
function img_find() {
var imgs = // the result of the checking of the textarea
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
return imgSrcs;
}
我該如何實現?
解決了
通過將其附加到另一個隱藏的div上,如下所示:
$('#hiddenContent').append $('textarea[name=content]').val() $img
= $('#hiddenContent').find('img') $("#hiddenContent > img").each (i, ele) ->
html = '<div class="image">
<img src="' + $(ele).attr('src') + '" class="thumbnail" width="100" title="Click to remove" />
<p>Image location: <b>' + $(ele).attr('src') + '</b> (copy <b>bolded</b> text to use on your content)</p>
<p><small>click image to remove</small></p>
</div>'
$('.contentImages').append html
function getSrc(textarea) {
var temporaryElement = document.createElement('div');
temporaryElement.innerHTML = textarea.value;
var images = temporaryElement.getElementsByTagName('img');
var output = [];
for (var i = 0; i < images.length; i++) {
output.push(images[i].src);
}
return output;
}
console.log(getSrc(document.getElementById('textarea')));
更新!
您可以使用CSS選擇器querySelectorAll()
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelectorAll
例如使用lodash unescape
<textarea id="content">
<p>..random content..</p>
<img src="myimage1.jpg" />
<p>..random content..</p>
<img src="myimage2.png" />
<p>..random content..</p>
</textarea>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.3.0/lodash.min.js"></script>
<script>
function img_find(id) {
var dom = document.getElementById(id);
var e = document.createElement('div');
e.innerHTML = _.unescape(dom.innerHTML); // Or use regex to replace < to < and > to >
var imgs = e.querySelectorAll('img');
var srcCollection = [];
for (var i = 0; i < imgs.length; i++) {
srcCollection.push(imgs[i].src);
}
return srcCollection;
}
img_find('content'); // ["myimage1.jpg", "myimage2.jpg"]
</script>
這是您應該使用正則表達式執行的操作:
JSFIDDLE: http : //jsfiddle.net/ewh8qe0t/1/
function img_find() {
var imgs = '<p>..random content..</p><img src="myimage1.jpg" /><p>..random content..</p><img src="myimage2.png" /><p>..random content..</p>';
var regex=/src="([A-z]+\d*\.[A-z]{3})"/g;
var imgSrcs = [], found;
while (found = regex.exec(imgs)) {
imgSrcs.push(found[0].split('=')[1].replace(/"/g,''));
}
return imgSrcs;
}
alert(img_find());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.