我试图掌握正确的jQuery语法和函数。我不确定我是否能以有效的方式做到这一点。这是我的函数,我将其存储为变量,因此我可以重复它:
var addProduct = function() {
$('#' + thisProduct).addClass('added');
$('#' + thisProduct + ' .more-info').addClass('hide');
$('#' + thisProduct + ' .panel-collapse').removeClass('in');
};
然后这就是我使用它的方式:
$('#purple-shirt .add').click(function(){
thisProduct = 'purple-shirt';
addProduct();
// plus something unique to this product
$('.something-different').show();
});
...
$('#green-shoe .add').click(function(){
thisProduct = 'green-shoe';
addProduct();
// plus something unique to this product
$('.another-thing').addClass('foo');
});
我觉得这可能是一种非常奇怪的方式吗?我每次都必须重新定义变量。
我想也许我可以做每个功能,就像这样:
$('.add').each(function(){
$(this).parent().click(function() {
});
});
但是因为一些"产品而被淘汰了#34;除了重复功能之外,它将具有独特的动作,它们并不总是与parent()或最接近的()等直接相关......每种不同的产品都会发生很多事情。
我使用作品的代码 - 我不确定它是正确的方式还是效率很高。
谢谢!
答案 0 :(得分:1)
您可能希望将变量传递给addProduct
函数,因此您不必再次创建变量。
var addProduct = function(thisProduct) {
$('#' + thisProduct).addClass('added');
$('#' + thisProduct + ' .more-info').addClass('hide');
$('#' + thisProduct + ' .panel-collapse').removeClass('in');
};
使用它:
addProduct('purple-shirt');
甚至更好:
var addProduct = function(thisProduct) {
var $product = $('#' + thisProduct);
$product.addClass('added');
$('.more-info', $product).addClass('hide');
$('.panel-collapse', $product).removeClass('in');
};
答案 1 :(得分:0)
如果你这样做怎么办?
var addProduct = function(productName) {
$('#' + productName).addClass('added');
$('#' + productName + ' .more-info').addClass('hide');
$('#' + productName + ' .panel-collapse').removeClass('in');
};
$('.add').click(function(event){
addProduct(event.toElement.parentNode.id);
});
或
$('.add').parent().click(function(event){
addProduct(event.toElement.id);
});
答案 2 :(得分:0)
我在这里写一个替代方案: http://jsfiddle.net/xw85bdkc/2/
(function () {
var extra = {
green: function () {
//put extra codes
console.log('green callback');
}
};
$('.add').parent().on('click', function (e) {
var product = e.currentTarget;
addProduct(product, extra[product.id]);
});
function addProduct(product, callbackExtra) {
$(product).addClass('added');
$(product).find('.more-info').addClass('hide');
$(product).find('.panel-collapse').removeClass('in');
if (callbackExtra) {
callbackExtra();
}
}
})();
)