Javascript动态地将值传递给jquery方法
javascript passing values dynamically to a method jquery
$(document).bind('pageinit', function () {
var vendor_id = $.urlParam('vendor_id');
$.ajax({
type: "GET",
url: "http://testservice/testmenu",
data: {
vendor_id: vendor_id
},
error: function () {
alert("Could not get the menu : " + url);
},
success: function parseXml(xml) {
var jsonData = $.parseJSON(xml);
$(jsonData).each(function (index, post) {
$(post).each(function (index, row) {
var finalString = [];
for(var index = 0; index < row.menu.length; index++) {
finalString.push('<div id="collapsibleMenu" data-mini="true" data-role="collapsible" data-inset = "true" data-content-theme="g">');
finalString.push('<h3>' + row.menu[index].category_name + '</h3>');
finalString.push('<ul id="menuDetails" data-role="listview">');
for(var j = 0; j < row.menu[index].products.length; j++) {
var output = ['<li data-icon="addToCart" id="addToCart"> <a href="javascript:test("+row.menu[index].products[j].prod_id")"><p>' + row.vendor_menu[index].products[j].prod_name + '</p><p> $' + Number(row.vendor_menu[index].products[j].price).toFixed(2) + '</p></a>' + '</li>'];
finalString.push(output);
}
finalString.push('</ul></div>');
}
$('#output').append(finalString.join(''));
});
});
$('#output').trigger('create');
}
});
});
function test(prod_id) {
alert("entered test " + prod_id);
addToCart(prod_id, 1);
}
在以下代码中,我做了以下操作:
<a href="javascript:test("+row.menu[index].products[j].prod_id")">
这显然给了我一个错误。关键是,我需要将prod_id动态地传递到javascript测试方法中。我不知道该怎么做。如果我只是调用test而不传递prod_id,它工作得很好。请帮助!
尝试删除参数中的引号
<a href="javascript:test('''+row.menu[index].products[j].prod_id+''')">
这看起来是使用模板引擎的完美理由。您可以像这样使用Jade模板:
for post in posts
for row in post
for menu in row.menu
#collapsibleMenu(data-mini="true", data-role="collapsible", data-inset="true", data-content-theme="g")
h3= menu.category_name
ul#menuDetails(data-role="listview")
for product in menu.products
li#addToCart(data-icon="addToCart")
a(href="#", data-product-id=product.prod_id)
p= product.prod_name
p= '$' + Number(product.price).toFixed(2)
那么你可以简化你的$.ajax
调用:
$.ajax({
// ...
dataType: 'json',
success: function(data) {
$('#output').append(templateFunction(data));
}
});
对于click事件,使用事件委托:
$('#output').on('click', 'a[data-product-id]', function() {
addToCart(Number($(this).data('product-id')), 1);
});
容易,是吗?现在将所有id
s更改为类,因为id
s必须是唯一的,并且您的不是!
相关文章:
- 如何在扩展jQuery方法时传递参数
- 用jQuery方法扩展Zepto.js?scrollTop()
- 如何使用页面's的jQuery方法
- 在 JQUERY 中创建 HTML 后,Jquery 方法不起作用
- 下拉 jquery 方法发布表单不起作用
- jQuery方法未按预期工作-toggleClass
- jQuery 方法调用了两次
- jQuery方法添加一个TextBox
- 在coffeescript中链接jquery方法和参数
- 在jQuery方法中编写自定义属性的正确语法是什么
- 我的jquery方法没有'不起作用
- jQuery方法找不到选择器
- 单击按钮后需要jQuery方法重定向-ASP.NET、VB.NET、jQuery、Javascript
- 如何在jquery方法中创建一个if语句
- 在jQuery方法中实现Javascript变量
- 使用参数作为jQuery方法
- 对从Ajax返回的数据使用Jquery方法,不打印数据
- 如何通过 .ajax() jQuery 方法获取 Carrierwave 上传到 Amazon S3 的图像的 URL
- 如何调用 jQuery 方法
- 插件中的元素不接受 jQuery 方法