【发布时间】:2015-05-30 21:52:23
【问题描述】:
我正在编写一个在“点击”事件上调用的 Jquery 函数。该函数需要用到this,所以可以引用点击的元素:
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"));
});
我该怎么做?此外,JSlint 说我的变量“可能严格违反”。我该如何解决这个问题?
我尝试过的步骤
- 使用提到的 .apply(this) here。
- 把$this放在函数中,这样就可以传入(as mentioned here)
【问题讨论】:
-
使用online version of JSLint,我无法用您的代码生成“可能严格违反”警告。
-
我已经更新了你的小提琴,检查这里jsfiddle.net/jwd1zb11/3
标签: javascript jquery this