$(document).on('click', '.title', function(){
var fn = $(this).attr('data-fn');
window[fn]();
});
function goUp() {
console.log('up');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title' data-fn='goUp'>lorem</div>
上面的方法有效,但我需要一些关于 goUp
函数的参数。例如:
<div class='title' data-fn="goUp('gold')">lorem</div>
function goUp(item) {
console.log(item);
}
在控制台中期待 gold
但我收到错误。
有什么帮助吗?
最佳答案
您的代码没有任何约束力。唯一的引用是 data-fn
中的字符串,正如我所说,它只是一个字符串!
您使用 JQuery 获取该字符串,并使用该键在 window
对象中查找任何属性。如果找到它,则执行该函数。
这没有什么不同:
const foo = "bar";
window.bar = "hello world";
console.log(window[foo]); // hello world
如您所知,您的 html 不知道 data-fn 是否为函数,是否有参数。
但是,您可以添加更多属性并将其用作参数:
$(document).on('click', '.title', function() {
var fn = $(this).attr('data-fn');
var arg1 = $(this).attr('data-arg1');
window[fn](arg1);
});
function goUp(arg){
console.log('up', arg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title' data-fn='goUp' data-arg1="gold">lorem</div>
关于javascript - 如何在窗口函数上传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54562449/