假设我已经使用 php 循环创建了一系列图像 ->
<img src="http://..._1.jpg" class="profile-thumb" id="12345678">
<img src="http://..._2.jpg" class="profile-thumb" id="12345677">
<img src="http://..._3.jpg" class="profile-thumb" id="12345676">
用户可以通过单击 jquery 样式来选择图像元素 ->
$(".profile-thumb").click(function () {
if ($(this).hasClass("active")) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
这样,当您单击图像时,它会向图像元素添加“.active”类 ->
<img src="http://..._3.jpg" class="profile-thumb active" id="12345676">
如何将所有选定的元素 ID 传递到一个数组中,以便在 PHP 的表单处理中使用?
用户旅程:
单击照片 -> 将 ID 添加到数组 -> 单击提交按钮 -> 使用 POST 数组对所有 ID 执行某个功能(例如,使用标识为事件的 ID 向所有用户发送电子邮件)
我想通过 AJAX 调用将数组传递到循环并将输出回显到 #post-info div ->
$.get('post.php', function(data) {
$('#post-info').html(data);
});
然后我将如何使用 foreach 循环读取 POST 数组?
解决方案:
HTML:
<button id="share" class="off">
<span>Sharer</span>
</button>
<div id="sharer">
<!-- Array will echo here -->
</div>
Javascript:
$("#share").click(function () {
//Create var array
var list = $('.active-profile').map(function(){return this.id;}).toArray();
$.post('sharer.php', {ids:list}, function(data) {
$('#sharer').html(data);
});
});
PHP (sharer.php)
foreach ($_POST['ids'] as $id) {
echo 'ID: ';
echo $id;
}
javascript 数组(列表)通过 jquery POST 发送并在 #sharer div 中回显
最佳答案
$('.profile-thumb.active').map(function(){return this.id}).toArray();
此外,您可以简单地使用:
,而不是if-hasClass-removeClass-else-addClass
$(".profile-thumb").click(function () {
$(this).toggleClass("active");
});
演示:http://jsfiddle.net/ErVbS/
关于php - 将元素 ID 传递到数组中以进行 POST 表单处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843383/