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

时间:2019-07-11 09:29:26

标签: javascript jquery function

我做了一个非常简单的自定义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)而不是测试undefined
  • eval(b)返回我height is not defined

以下是一个尝试方法:

$('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>

2 个答案:

答案 0 :(得分:1)

如上所述,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>

答案 1 :(得分:0)

您必须至少定义一次高度变量。像这样。

$(document).ready(function(){
		var height = 0;
		$('button').on('click',function() {
  			$('div').resetCss(height);
		});
		$.fn.resetCss = function(b) {
			
		    if (b){
		      let a=this.style.b;
		    }

		    this.removeAttr('style');

		    if(b) {
		      this.style.b = a;
		    }
		  }
	})
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>