【问题标题】:Multiple Functions on a .on() without impacting scope.on() 上的多个函数而不影响范围
【发布时间】:2019-04-08 09:59:41
【问题描述】:

我目前正在制作一个动态网页,并尝试在单击具有 class=application 的元素时运行多个功能。以下代码有效,但重复性很高。

$(document).on("click", ".application", renderImage);
$(document).on("click", ".application", renderText);
$(document).on("click", ".application", renderCodeButton);
$(document).on("click", ".application", renderAppButton);

我试图将这些函数放在一个主函数中并使用 .on() 运行它,但是因为我使用 $(this).attr 来提取嵌套在主函数中的渲染函数的信息会破坏范围。

这里是 renderImage 函数,虽然它们都非常相似:

function renderImage () {
  $(".appPicture").empty();
  console.log(this);
  let applicationPic = $(this).attr("data-image")
  let img = $("<img>");
  img.addClass("appPic")
  img.attr("src", applicationPic);
  $(".appPicture").append(img);
}

有没有一种方法可以通过单击事件运行多个函数,或者有一种方法可以将函数嵌套在主控中而不影响范围?

【问题讨论】:

    标签: jquery function scope onclick this


    【解决方案1】:
    $(document).on("click", ".application", function(){
        let scope = this;
        renderImage(scope);
        renderText(scope);
        renderCodeButton(scope);
        renderAppButton(scope);
    });
    
    function renderImage (scope) {
        $(".appPicture").empty();
        console.log(scope);
        let applicationPic = $(scope).attr("data-image")
        let img = $("<img>");
        img.addClass("appPic")
        img.attr("src", applicationPic);
        $(".appPicture").append(img);
    }
    

    你可以这样做

    【讨论】:

    • 我试过了,但它改变了范围,所以 $(this) 不再是我点击的项目,而是窗口。
    • 我编辑答案,你的函数应该有接受你想要的范围的参数..
    • 完美运行!谢谢。
    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多