我正在使用此代码进行调试...
$(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);
它总是返回" undefined" $el.className
和$el.id
。
如何让它返回我点击过的元素(div)的id和类?
我尝试了$el
和.id
的多种变体,但似乎没有任何效果。
答案 0 :(得分:1)
您正在混合使用jQuery和vanilla javascript属性。 className
是vanilla,$(this)
创建一个jQuery对象。
要么改变
$el.className
到
$el.attr('class')
或者如果您想使用className
:
var $el = $(this);
到
var $el = this;
(虽然这也需要更改代码的其他部分)
答案 1 :(得分:1)
尝试如下:
$(function() {
$("div").click(function() {
var name = this.name;
var cls = this.className;
var id= this.id;
alert("Name: " + name + " / Class: " + cls + " / Id: " + id);
});
});