$("#like_answer_button").removeAttr("disabled");
$('#like_answer_button').click(function(e)
{
var id = $(this).closest('.box').data('id');
var url = "https://www.sdkwf.de/jquery/good_answer.php?answer_user=" + id;
var val = parseInt($("#like_answer_button").val(), 10);
$.post(url,{op:"<?php echo $ask; ?>"},function(data)
{
$("#status").html("");
val = val+1;
$("#like_answer_button").val(val);
$("#like_answer_button").attr("disabled", "disabled");
$("#like_answer_button").css("background-image","url(https://www.sdkwf.de/img/icon.png)");
})
});
如果在PHP(同时)中重复使用此代码的许多不同按钮,我知道如何使这个脚本工作吗?
<div class="box" data-id="'.$id.'">
<input type="submit" class="like" name="like_answer_button" value="10" id="like_answer_button" />
它仅适用于第一个按钮/输入,但其他按钮/输入不起作用。我想是因为like_answer_button是为第一个保留的吗?
答案 0 :(得分:-1)
HTML - 不要为输入重复相同的ID。确保名称和ID在您需要时是唯一的。
<div class="box" data-id="'.$id.'">
<input type="submit" class="like" value="10" />
<div class="box" data-id="'.$id.'">
<input type="submit" class="like" value="11" />
<div class="box" data-id="'.$id.'">
<input type="submit" class="like" value="12" />
JS - 在javascript中使用类选择器而不是特定的元素id
$('.like').click(function(e)
{
var id = $(this).closest('.box').data('id');
var url = "https://www.sdkwf.de/jquery/good_answer.php?answer_user=" + id;
var val = parseInt($(this).val(), 10);
$.post(url,{op:"<?php echo $ask; ?>"},function(data)
{
$("#status").html("");
val = val+1;
$(this).val(val);
$(this).attr("disabled", "disabled");
$(this).css("background-image","url(https://www.sdkwf.de/img/icon.png)");
})
});
答案 1 :(得分:-1)
您已使用$(this)
进行closest('.box')
来电。这是对点击的like_answer_button
的引用。在var中捕获它,并在post回调中使用它:
$("input[type='submit'].like").click(function(e)
{
var button = $(this);
var id = button.closest('.box').data('id');
var url = "https://www.sdkwf.de/jquery/good_answer.php?answer_user=" + id;
var val = parseInt(button.val(), 10);
$.post(url, { op: "<?php echo $ask; ?>" }, function(data)
{
$("#status").html("");
val = val + 1;
button.val(val);
button.attr("disabled", "disabled");
button.css("background-image","url(https://www.sdkwf.de/img/icon.png)");
})
});
答案 2 :(得分:-1)
// click handler
jQuery('.like').on('click', function(e){
// get the value of the input
var val = jQuery(e.currentTarget).val();
// find the element that contains the data-id and do something to it
jQuery('[data-id="'+ val +'"]').hide();
});
&#13;
<?php $iterator = 0; ?>
<?php foreach($array as $key=>$value): ?>
<div class="box" data-id="<?php echo 'target-'.$iterator; ?>">
<input type="submit" class="like" value="<?php echo 'target-'.$iterator; ?>" />
<?php $iterator++; ?>
<?php endforeach; ?>
&#13;