【问题标题】:How to find a dom element inside another dom element?如何在另一个 dom 元素中找到一个 dom 元素?
【发布时间】:2016-09-16 22:35:19
【问题描述】:

我在 ajax 调用中返回了 html:

$.ajax({
    url: '/get-html',
    dataType: 'html',
    success: function(html) {
        html = $(html);
        ....

在成功方法中,我希望在 html var 中的容器 div 内找到 img 标签,并将其更改为 alt 标签。

如果我这样做:

html.find('img').attr('alt', 'new alt');

我们会更新所有图片的 alt。如何仅指定容器 div 的 alt?我试过这个:

html.find('.container img').attr('alt', 'new alt');

但它不起作用。

仅供参考,这里是 ajax 调用中返回的 HTML 示例:

<div class="container">
    <img src="" alt="PLEASE CHANGE THIS ALT">
</div>
<img src="" alt="LEAVE MY ALT ALONE">
<img src="" alt="LEAVE MY ALT ALONE">

【问题讨论】:

  • 是的,100% 确定,该示例不起作用。
  • .container 是包装器,而不是 html 的子级。所以使用html.filter('.container').find('img')
  • eisbehr 这不起作用。
  • 哦,@A.Wolff 是正确的,我错了......
  • A.沃尔夫 - 你是对的,谢谢。

标签: javascript jquery


【解决方案1】:

试试这个 -

var html = '<div class="container"><img src="" alt="PLEASE CHANGE THIS ALT"/></div><img src="" alt="LEAVE MY ALT ALONE"/><img src="" alt="LEAVE MY ALT ALONE"/>';

//Print Your html Code before changing alt attr.
$('body').append(html);
$('body').append('<hr/>');

html = $(html);

//Check img inside .div and change attr
html.children('.container img').each(function() {
  $(this).attr('alt', 'new alt');
  //Log changed attr
  console.log($(this).attr('alt'));
});
//Print Your html Code after changing alt attr.
$('body').append(html);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2014-09-30
    • 2011-04-01
    • 2012-04-17
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多