gpt4 book ai didi

javascript - 将 javascript 参数字传递给自定义函数

转载 作者:行者123 更新时间:2023-12-02 23:20:09 26 4
gpt4 key购买 nike

我制作了一个非常简单的自定义 Jquery 函数,可以重置 html 元素的内联样式。但是,我希望能够传递一个要排除的参数,以便“重置”将避免它。

$.fn.resetCss = function(b) {
if (b != 'undefined'){
let a=this.style.b;
}

this.removeAttr('style');

if(b != 'undefined') {
this.style.b = a;
}
}

但是后来我通过传递(例如)高度时遇到了错误。

  • 我尝试了 if(b) 而不是测试 if undefined
  • eval(b) 返回我高度未定义

这是一个尝试的片段:

$('button').on('click',function() {
$('div').resetCss(height);
});
div {
width:100px;
height:50px;
background-color:#ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
$.fn.resetCss = function(b) {
if (b){
let a=this.style.b;
}

this.removeAttr('style');

if(b) {
this.style.b = a;
}
}
</script>

<button>go</button>
<div style='width:200px;height:100px;'>
</div>

最佳答案

正如评论所述,this 是一个 jQuery 对象。 jQuery 没有 style 属性。因此 this.style.anything 将导致空引用异常。

我还更新了您的函数。

$.fn.resetCss = function() {
var stylesToKeep = [].slice.call(arguments);

if (stylesToKeep.length > 0) {
this.each(function() {
let styles = {};
for (let i = 0; i < stylesToKeep.length; ++i) {
let key = stylesToKeep[i],
value = this.style[key];
// don't copy undefined and empty values
if (value) {
styles[key] = value;
}
}
this.removeAttribute("style");
Object.assign(this.style, styles);
});
} else {
this.removeAttr('style');
}

return this;
}


$('button').on('click', function() {
$('div').resetCss("height");
});
div {
width: 100px;
height: 50px;
background-color: #ddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>go</button>
<div style='width:200px;height:100px;'>
</div>

关于javascript - 将 javascript 参数字传递给自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56985992/

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