如何在jquery中获取元素的对象名称

时间:2013-04-05 14:52:54

标签: jquery html

我正在玩互联网上创建购物车的插件,插件(jquery代码)代码我非常确定在我的html中引用了我的'#featured'div标签但是我不是100%肯定。无论如何这是我的html,我称之为smartcart插件

  <script type="text/javascript">

$(document).ready(function(){
    // Call Smart Cart instead of features maybe something more higher up to include more features      
    $('#featured').smartCart();
    });
</script>
<div id="featured"></div>

这是我正在玩

的插件的嗤之以鼻
(function( $ ){

$.fn.smartCart =function() {
var options = $.extend({}, $.fn.smartCart.defaults, options);
return this.each(function() {

            var obj = $(this);
            alert(obj); 
};
})( jQuery );

有问题的代码是var obj = $(this)的地方,警报带回'对象对象',我试过attr('name')和.selector和prop。('name')他们要么带回空白或“未定义”。有人可以告诉我,我正确地认为'这'是指我的html中的特色div,以及为什么当我尝试从警报中取回它的名称时它不起作用。只是对象对象或未定义

1 个答案:

答案 0 :(得分:0)

您的div没有name属性,这就是undefined的原因。

此外,您在最后一行的第三行上错过了结束})

要回答您对this是否引用div元素的评论,答案是。没有必要再将它包装成一个jQuery对象(它已经是一个)。

首先添加它:

<div id="featured" name="foo"></div>

然后做:

(function( $ ){

    $.fn.smartCart =function() {
        var options = $.extend({}, $.fn.smartCart.defaults, options);
        return this.each(function() {

            var obj = $(this);
            alert(obj.attr("name")); 
        }); //you were missing this
    };
})( jQuery );