我正在使用这段代码来调试...
$(document).ready(function() {
$('.slider').slider();
});
$.fn.slider = function() {
return this.each(function() {
var $el = $(this);
var dragging = false;
var startX = $el.offset().left;
var startL = 0;
$el.mousedown(function(ev) {
dragging = true;
startX = ev.clientX;
startL = $(this).css('left');
alert("class: "+ $el.className +" id: " + $el.id);
});
$(document).mousemove(function(ev) {
if (dragging) {
var newLeft = parseInt(startL) + (ev.clientX - startX);
$el.css('left', newLeft );
}
}).mouseup(function() {
dragging = false;
});
});
}
注意:alert("class: "+ $el.className +"id: "+ $el.id);
它始终为 $el.className
和 $el.id
返回“undefined”。
如何让它返回我点击的元素 (div) 的 ID 和类?
我已经尝试了很多 $el
和 .id
的变体,但似乎没有任何效果。
最佳答案
您正在混合使用 jQuery 和 vanilla javascript 属性。 className
是普通的,$(this)
是一个 jQuery 对象。
要么改变
$el.className
到
$el.attr('class')
或者如果你想使用className
:
var $el = $(this);
到
var $el = this;
(尽管这也需要更改代码的其他部分)
关于javascript - 检索元素的类名和 ID 时,我总是得到 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22871514/