在不影响作用域的情况下对.on()执行多个函数



我目前正在制作一个动态网页,并试图在单击带有class=应用程序的元素时运行多个函数。下面的代码可以工作,但它非常重复。

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

有没有一种方法可以通过单击事件运行多个函数,或者在不影响作用域的情况下将函数嵌套在主函数中?

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

你可以做一些类似的事情

最新更新