jquery - .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 中?
解决方案
$(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);
}
你可以做这样的事情
推荐阅读
- html - 用于下划线的 Material UI CSS 动画
- actionscript-3 - 使用动作脚本 3 检测颜色
- python - ![远程拒绝] master -> master (pre-receive hook denied) 错误:未能将一些参考推送到“https://git.heroku.com/stark-dawn-54447.git”
- haskell - Haskell 检查嵌套数据
- android - 在Pagedlist Android中加载更多页面时需要回调
- python - 使用 pyomo 并行解决许多实例
- amazon-web-services - 通过站点到站点 VPN 从本地连接到 AWS s3
- python - 如何从 python 脚本中的单个 bibtex 输入字段获取可读的 unicode 字符串
- gist - 在 Medium 上使用 Github Gists 嵌入代码不起作用
- javascript - document.querySelectorAll 检索所有必需的元素