javascript - 如何从任何元素获取 img 标签?

标签 javascript jquery html

我想获取任意元素的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:这是该行中发生的事情:

请注意,在您的初始 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/

相关文章:

javascript - 滚动显示 'no elements found' ?

javascript - Bootstrap 开关无法处理 Ajax 数据

javascript - 在提交表单之前将复选框值组合成字符串

javascript - jquery 设置 tabindex 和游标

javascript - HTML:在表的 td 上覆盖 div

javascript - 获得每个 tr 的 td 值

html - 无法让我的导航越过在翻转时淡入的头部

javascript - 如何在 PHP 中接收 Ajax urlencode

javascript - JQuery 在按钮前隐藏/显示 Div

html - 如何使表格的外边框与 HTML 中的内边框颜色不同?