[英]Use this in a function without “Possible strict violation.”
I am writing a Jquery function that is called on a 'click' event. 我正在编写一个在'click'事件上调用的Jquery函数。 The function needs to make use of
this
, so it can refer to the clicked element: 该函数需要利用
this
,因此它可以引用clicked元素:
var allPanels = $('[data-display-mode~="accordion"] .unit-text').hide();
$('[data-display-mode~="accordion"] .unit').addClass("closed");
function accordion($this, $type) {
var $root;
var $body;
var $this = $(this);
//Change variables depending on function
if ($type === "stack") {
$root = $(this).parents(".unit");
$body = $(this).parents(".unit").find('.unit-text');
} else if ($type === "panel") {
$root = $(this);
$body = $(this).find('.unit-text');
}
if ($root.hasClass('closed')) {
allPanels.slideUp().parents(".unit").removeClass('open').addClass('closed');
$root.removeClass('closed').addClass('open');
$body.slideDown();
} else {
$root.removeClass('open').addClass('closed');
$body.slideUp();
}
}
// Call function on Click
$('[data-display-mode~="accordion"][data-display-mode~="stack"] .unit-heading').click(accordion("stack"));
$('[data-display-mode~="accordion"][data-display-mode~="panel"]').click(accordion("panel"));
});
How can I do this? 我怎样才能做到这一点? In addition, JSlint says I have "Possible strict violation" for my variables.
另外,JSlint说我的变量“可能严格违反”。 How can I fix this?
我怎样才能解决这个问题?
I have made a JSFiddle here 我在这里做了一个JSFiddle
What is important to know is that .click
need a function reference. 重要的是要知道
.click
需要一个函数引用。 What you are doing is calling a function that does not return any function reference. 您正在执行的是调用不返回任何函数引用的函数。
To achieve what you want, you can simply make accordion
return an other function. 为了实现您想要的,您可以简单地使
accordion
返回另一个函数。 You'll then have everything you want : 然后,您将拥有所需的一切:
function accordion($type) { //Removed the $this argument
return function(){ //That will be the function called when you click on the target
var $root;
var $body;
var $this = $(this);
//Change variables depending on function
if ($type === "stack") {
$root = $(this).parents(".unit");
$body = $(this).parents(".unit").find('.unit-text');
} else if ($type === "panel") {
$root = $(this);
$body = $(this).find('.unit-text');
}
if ($root.hasClass('closed')) {
allPanels.slideUp().parents(".unit").removeClass('open').addClass('closed');
$root.removeClass('closed').addClass('open');
$body.slideDown();
} else {
$root.removeClass('open').addClass('closed');
$body.slideUp();
}
}
}
If you check the console, you'll see that the $type
is ok. 如果您检查控制台,您会看到
$type
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.