我的代码出了什么问题?
var $slider = $('#gallery-slider');
$slider.addClass('someClass') //works fine
var $buttons = $('.btn-controls');
var $active_btn = $buttons[1];
alert($active_btn); // alert 'object HTMLButtonElement' i.e. element has been taken correctly
$active_btn.addClass('someClass') //causes en error '$active_btn.addClass is not a function'
答案 0 :(得分:2)
$buttons[1];
不会返回jquery对象,因此您无法通过它调用jquery方法。
使用
$buttons.addClass("someClass") //if you want to add class to all buttons
或
$buttons.eq(1).addClass("someClass") //if you want to add class to second element in the list of buttons
答案 1 :(得分:0)
使用正确的分号清理代码,并且.....必须通过jQuery object更改类。使用eq()
selector:
var $slider = $('#gallery-slider');
$slider.addClass('someClass'); //works fine
var $buttons = $('.btn-controls');
var $active_btn = $('.btn-controls').eq(1);
alert($active_btn); // alert 'object HTMLButtonElement' i.e. element has been taken correctly
$active_btn.addClass('someClass'); //causes en error '$active_btn.addClass is not a function'
答案 2 :(得分:0)
正如@Kartikeya Khosla所说,你需要将html对象转换为jquery对象
$($active_btn).addClass('someClass')