gpt4 book ai didi

javascript - 如何用变量替换 jQuery 事件名称

转载 作者:行者123 更新时间:2023-11-28 19:10:01 24 4
gpt4 key购买 nike

有没有办法用如下变量替换 jQuery 事件名称?如果有的话,怎么样?如果不是,为什么?

非常感谢。原代码:

var menu = $('.menu');
var search_bar = $('#search_bar');
var bar = $('#bar');
var icon = $('.myicon');

search_bar.focusin(function(){
search_bar.css('width','20%');
menu.css('width','80%');
bar.css('color', '#000);
icon.css('color', '#000);
});

我想要的代码:

function doSomething(tag, tagAction, actionAttributes) {
if ((tag) && (tagAction)) {
$(tag).???tagAction(actionAttributes.key, actionAttributes.val);
}
}

???tagAction 代表“css”,是否有通配符可以替换事件名称,或者我应该使用“switch”才能让下面的代码正常工作?

doSomething(".menu", "css", "{'width':'80%'}");

最佳答案

您可以使用bracket notation

function doSomething(tag, tagAction, actionAttributes) {
if ((tag) && (tagAction)) {
$(tag)[tagAction](actionAttributes.key, actionAttributes.val);
}
}

请注意,您尝试调用 doSomething 的方式将不起作用,因为 actionAttributes 变量是字符串,而不是对象。这样调用就可以了。

doSomething(".menu", "css", {key:'width', val:'80%'});

关于javascript - 如何用变量替换 jQuery 事件名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com