我的onClick功能未触发,当我通过Console手动触发时,出现以下错误:未捕获的SyntaxError:意外的数字
<div style="width:50%;float:left;padding:5px;" class="btn btn-default">
<center><b><i class="fa fa-thumbs-o-up" aria-hidden="true" onClick="like_post(<?php echo $PinnedObj->ID;?>,<?php echo $client->ID;?>)""></i>
JS功能:
script type="text/javascript" >
function like_post(PID, UID){
$.ajax({
url: "like.php",
type: "POST",
data: {'PID': PID, 'UID': UID, 'liked': '1'},
});
document.getElementById("like_button"+PID).value = parseInt(document.getElementById("like_button"+PID).value,10) + 1;
}
</script>
答案 0 :(得分:0)
你的问题是你已经使用了&#34;价值&#34;没有它的元素。 &#34;值&#34;只出现在元素中。你必须使用&#34;文本&#34;要更新它的元素。
第二个问题是你将元素的空文本与 相加1.未定义的parseInt(在你的情况下)给出NaN结果与&#34; 1&#34;给出&#34; NaN&#34;。
function like_post(pid, uid) {
var $btn = $('#like_button'+pid);
$.post("like.php", {"PID": pid, "UID": uid, "liked": "1"}, function(r) {
$btn.text(parseInt($(btn).text()||0)+1);
});
}
更新。但更漂亮的是,如果&#34; like.php&#34;将返回喜欢的数量
function like_post(pid, uid) {
var $btn = $('#like_button'+pid);
$.post("like.php", {"PID": pid, "UID": uid, "liked": "1"}, function(r) {
$btn.text(r);
});
}
答案 1 :(得分:0)
你正在使用jquery和ajax,所以你可以扩展jquery这样的添加计数器函数。
jQuery.fn.extend({
add: function() {
return this.each(function() {
var element = $(this);
if ( element .is( "input" ) ) {
element.val(parseInt((element.val() || 0)) + 1)
}
if ( element .is("button") ) {
element .text(parseInt((element.text() || 0)) + 1)
}
});
}
});
你可以用作
var $btn = $('#like_button'+pid);
$btn.add();