【发布时间】: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