我有一个由类和数据自定义属性标识的项目列表,如下所示:
<div class="matrix_type" id="12" data-matrix-value="7"></div>
<div class="matrix_type" id="189" data-matrix-value="4"></div>
<div class="matrix_type" id="12090" data-matrix-value="10"></div>
<div class="matrix_type" id="1234" data-matrix-value="2"></div>
我想使用按钮来触发AJAX帖子<button id"send_matrix">Send<button>
单击按钮后,我希望将每个“div”与其值相关联,该对象可以在AJAX请求中与其他数据一起发送。
任何指南?
答案 0 :(得分:1)
假设你想获得所有的div并迭代获取所有值,然后将它们发布到&#39; one&#39;对象,执行以下操作:
$('#send_matrix').click(function(){
// We post this to the server
var postObject = {};
//Get all the divs with the class of 'matrix_type' and iterate through
$('.matrix_type').each(function(){
//Get the id of the current div (please make them unique!)
var id = $(this).attr('id');
//Get the matrix value of the current div
var matrixValue = $(this).data('matrix-value');
//Add a new key-value pair to the postObject
postObject[id] = matrixValue;
});
//Replace this with the url you post the data to
var url = 'www.something.com'
//Post the data to the server
$.post(url, postObject, function(data, status){
//Show the result of the attempted post (success or failure)
alert("Data: " + data + "\nStatus: " + status);
});
});