Передача слова параметра JavaScript в пользовательскую функцию - PullRequest
0 голосов
/ 11 июля 2019

Я сделал очень простую пользовательскую функцию 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 ]

1 голос
/ 11 июля 2019

Как прокомментировано, 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>
0 голосов
/ 11 июля 2019

Вы должны определить переменную высоты хотя бы один раз. Как это.

$(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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...