我想获取任意元素的img标签属性值,img标签可以多于1个,也可以随机化。 喜欢,
<div> hellow <img src='icons/smile.png' title=':)'> how are u <img src='icons/smile2.png' title=':D'></div>
我想获取它们的 title
属性值,然后将所有现有的 div 数据存储在一些 var currentHTML;
中。
然后插入任何元素,就像 $('#div').html(currentHTML);
输出应该是这样的
hellow :) how are u :D
我该怎么做?
提前致谢。
最佳答案
试试这个:
$("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
Fiddle .它只是循环遍历每个图像并用它自己的 title
属性替换它(用 replaceWith()
)。
更新:
事情变得更加复杂。检查this snippet :
// The text result you want
var currentHTML = "";
// Instead of search for each image, we can search of elements that
// contains images and you want to get their text
$(".images").each(function()
{
// Check note #1
var cloned = $(this).clone().css("display", "none").appendTo($("body"));
// Here we select all images from the cloned element to what
// we did before: replace them with their own titles
cloned.find("img").each(function()
{
$(this).replaceWith($(this).prop("title"));
});
// Add the result to the global result text
currentHTML+= cloned.html();
});
// After all, just set the result to the desired element's html
$("#div").html(currentHTML);
注意 #1:这是该行中发生的事情:
var cloned =
在这里我们创建一个 var,它将接收一个克隆的元素;- 克隆的元素将成为当前元素
$(this).clone()
; - 必须隐藏此元素
.css("display", "none")
; - 然后附加到文档的主体
.appendTo($("body"));
.
请注意,在您的初始 html 中,包含图像的 div
接收到 images
类:
<div class="images"> hellow <img src='icons/smile.png' title=':)' /> how are u <img src='icons/smile2.png' title=':D' /></div>
因此您可以对多个元素执行此操作。我希望这会有所帮助。
关于javascript - 如何从任何元素获取 img 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29648063/