我缺少一些 JavaScript 基础知识。我经常使用下面的代码,我想简化它:
$("#someLink").on('click', function (e) {
e.preventDefault();
var link = $(this).attr('href');
$.confirm({
confirm: function () {
title: 'I would like a variable here'
window.location.href = link;
}
});
})
类似于:
//somehow define myConfirm function here
//so the code below can be used in a similar simple way and it would do the same as the first code snippet in the post.
$("#someLink").myConfirm(title);
也许这会起作用,但这是最好的方法吗?:
function myConfirm($object,title){
$object.on('click', function (e) {
e.preventDefault();
var link = $(this).attr('href');
$.confirm({
confirm: function () {
title: title
window.location.href = link;
}
});
})
}
myConfirm($linkObject, title);
我不确定这个东西 $.confirm
是如何被调用的。它是一个插件吗?它也可以以某种方式制作链接吗?我会自己更多地研究这个问题,但我认为这个问题包含多个 javascript 主题,我不知道从哪里开始。
最佳答案
是的,jQuery plugin .
$.fn.myConfirm = function(title) {
this.on('click', function (e) {
// ...
});
};
$('#someLink').myConfirm(title)
请注意,这不适用于纯 JS,因为它是 jQuery 功能。
关于Javascript 基础知识 – 有没有一种方法可以在不使用标准函数的情况下重用代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556420/