我正在玩互联网上创建购物车的插件,插件(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,以及为什么当我尝试从警报中取回它的名称时它不起作用。只是对象对象或未定义
答案 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 );