[英]When retrieving the class name and id of an element I always get undefined
我正在使用此代碼進行調試...
$(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
返回“未定義”。
如何獲取返回單擊的元素(div)的ID和類的信息?
我嘗試了$el
和.id
許多變體,但似乎沒有任何效果。
您正在混合使用jQuery和香草javascript屬性。 className
是vanilla, $(this)
創建一個jQuery對象。
要么改變
$el.className
至
$el.attr('class')
或者如果您想使用className
:
var $el = $(this);
至
var $el = this;
(盡管這也需要更改代碼的其他部分)
嘗試如下:
$(function() {
$("div").click(function() {
var name = this.name;
var cls = this.className;
var id= this.id;
alert("Name: " + name + " / Class: " + cls + " / Id: " + id);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.