使用while循环创建多个按钮,但只有第一个按钮在使用.onclick函数时才会响应 [英] creating multiple button using while loop but only first button is responsive when using .onclick function

查看:116
本文介绍了使用while循环创建多个按钮,但只有第一个按钮在使用.onclick函数时才会响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我在一个太小的问题上运行,我在创建喜欢和不喜欢的功能,所以我创建了一个while循环,为每个标签创建了喜欢和不喜欢但只有第一个按钮在使用时响应.onlick = function

hi guys i ran in too small issue where i am creating like and dislike function so i created an while loop that created like and dislike for every tag but only the first button are responsive when using .onlick = function

if (mysql_num_rows($res) > 0){
while ($row = mysql_fetch_assoc($res)) {
//blah blah blah
$categories .= "<a href='view_category.php?cid=".$id."' class='cat_links'>".$title." - <font size='-1'>".$description." </a> </font> <div class='rating'><input type='button' id='like1' value='like' /><span id='temp_rating'> ".$rating." </span><input type='hidden' name='cid' id='cid' value='".$id."'/><input type='button' value='dislike' /></div>";
//blah blah blah
}
}

这个

我的javascript代码是

and the my javascript code is

<script src="ajax.js"></script>
<script>
var submitEvent = document.getElementById("like1").onclick = function(){

    likemsg(HTTP);
};

</script>

ajax.js

function likemsg(){
    var temp_rating = 1;
    var cid = encodeURIComponent(document.getElementById('cid').value);

    var url = "category_like_parse.php?temp_rating="+temp_rating+"&cid="+cid;

    alert();

    HTTP.onreadystatechange=function()
    {
        if (HTTP.readyState==4 && HTTP.status==200)
        {
            document.getElementById("temp_rating").innerHTML=HTTP.responseText;
        }
    }

HTTP.open("POST", url ,true);
HTTP.send();

}

并转到category_like_parse.php将+1保存到数据库和回应它,它显示它,但只有第一个像按钮,其余的没有响应我得到这个结论,因为我使用alert();这只适用于第一个和其余的工作。我做错了什么。

and goes to category_like_parse.php saves +1 to database and echo it and it displays it but only for first like button the rest are unresponsive i got to this conclusion because i used alert(); which only worked for the first one and the rest dint. am i doing anything wrong.

推荐答案

那是因为你创建了多个具有相同id的按钮,因为id无效必须是唯一的。

that's because you're creating number of buttons with the same id and that is invalid because id must be unique.

而是将名称分配给相似的按钮。

instead assign name to like buttons.

<input type='button' id='like1' name='like' value='like' />

var likeBut= document.getElementsByName("like");
for(var i=0;i<likeBut.length;i++){
   likeBut[i].onclick = function(){
      likemsg(HTTP);
   }
}

这篇关于使用while循环创建多个按钮,但只有第一个按钮在使用.onclick函数时才会响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆