首页 > 解决方案 > .on() 上的多个函数而不影响范围

问题描述

我目前正在制作一个动态网页,并在单击带有 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);
}

有没有办法通过单击事件运行多个函数,或者在不影响范围的情况下将函数嵌套在 master 中?

标签: jqueryfunctionscopeonclickthis

解决方案


$(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);
}

你可以做这样的事情


推荐阅读