【问题标题】:jQuery and the scope of thisjQuery 和 this 的范围
【发布时间】:2017-05-13 04:07:15
【问题描述】:

我在这个函数的范围内遗漏了一些东西,我有一个 cms 可以自动将类添加到图像但不会但不会更改它们的对齐方式,因此文本不会正确环绕它们。我不能简单地使用 $("img").attr("align","left");因为这会改变页面上的每张图片,也就是说使用上下文“img”,这不像我想象的那样工作,而且完全没有任何作用。

function align_image(){
    console.log("func called");
    if($("img").length){
        if($("img").hasClass("alignleft")){
            $("img", this).attr("align","left");
            console.log("aligned left!")
    }

       if($("img").hasClass("alignright")){
           $("img", this).attr("align","right");
           console.log("aligned right!");
       }
   }
}
align_image();

有没有人知道我可以如何更改每个 img 以与其关联的类保持一致?奖励积分为什么它有效。

编辑:codepen 演示

【问题讨论】:

  • 问题不在于改变图像对齐方式,没有“this”它可以正常工作问题是,使用“this”我目前的方式不会选择任何东西,如果我不使用“this ",它会选择页面上的每个图像标签并重新对齐。因此,如果我有 50 个 img 标签,则无论找到最后一个标签,它们都会对齐。
  • 您可以使用类标识符添加属性,如 $('img.alignleft').attr('align','left');和类似的 alignright 类

标签: jquery scope this


【解决方案1】:

我认为您可以遍历每个图像,并且迭代器函数使用“this”引用来引用 img DOM 元素。像这样的:

function align_image(){
    console.log("func called");
    if ($(this).hasClass('alignleft')) {
        $(this).attr("align","left");
    }

    if ($(this).hasClass('alignright')) {
        $(this).attr("align","right");
    }
}

$('img').each(align_image);

正如 cmets(和其他答案)中所建议的,您还可以使用特定的 jQuery 选择器来完成相同的操作:

$('img.alignleft').attr("align","left");
$('img.alignright').attr("align","right");

最后,根据w3schools,img align 属性已被弃用,而应使用 CSS 属性。像这样的东西应该可以工作:

img.alignleft {
  float: left;
}

img.alignright {
  float: right;
}

我希望这能捕捉到所有的角度。

【讨论】:

  • 这将遍历所有图像,并检查每个图像的类。如果你想要一些捷径,你可以这样做: $('img.alignleft').attr("align", "left") 和 $('img.alignright').attr("align", “对”)。这将在所有带有 alignX 类的 img 标签上设置对齐属性。当然,这也可以用 css 样式表来完成,对吧?
  • 太好了!我很高兴它有效!旁注:我实际上建议使用我评论中建议的选择器。答案中列出的方法与您的原始逻辑更匹配。选择器提供了一种更简洁的方法,通过单个函数调用来操作多个 DOM 元素,我相信这是 jQuery 的最大优势之一。祝你好运!
  • 对不起,当你说它可以用 css 完成时,我知道 text-align (不起作用),但你是说还有其他东西可以改变 align 属性在图像上?我宁愿用 css 做事,也不愿用 js。
  • 我刚刚在这里 (w3schools.com/tags/att_img_align.asp) 发现 img "align" 属性已被弃用(尽管主流浏览器仍然支持)。它建议对于垂直对齐,使用“vertical-align”css 属性。对于水平对齐,建议使用“float”css 属性(float: left or float: right)。
  • 我已经用似乎可以解决问题的所有不同解决方案更新了答案。我希望它们都清晰易懂。
【解决方案2】:

试试这个。我觉得对你有帮助

function align_image(){
    console.log("func called");
   if ($('img').hasClass('alignleft')) {
    $(this).attr("align","left");
    }

   if ($('img').hasClass('alignright')) {
    $(this).attr("align","right");
    }
}
align_image();

【讨论】:

  • 这是我尝试的第一件事,我认为这会选择它当前正在侦听的任何图像并进行更改。在那种情况下,它似乎不知道“this”是什么。
  • 你能提供demo吗,我可以帮你。
  • 我会尽快弄一个
【解决方案3】:

您最好使用过滤器方法来查找您的元素并添加这样的属性:

$("img").filter('.align-right').attr("align","right") ;                           
$("img").filter('.align-left').attr("align","left") ;

See here

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2011-11-29
    • 2013-07-02
    • 2018-09-05
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多