-1

我正在尝试创建一个投票系统。每当用户填写带有标题和您可以投票的两个可能选项的表单时,数据就会使用 ajax 附加到页面上的 div 元素中。使用单选按钮,当用户单击两个可能的投票选项之一(一个输入值为 0,另一个值为 1)时,我想将值(0 或 1)发送到 php 文件,该文件然后将被插入到数据库中。

这是我单击输入字段时发生的情况: https ://jsfiddle.net/crdiling/dczup26h/36 HTML:

<div class='display-polls-container'>
</div>
<button id='user-created-poll'>Click for new poll</button>

Javascript:

$("#user-created-poll").click(function() {

  $(".display-polls-container").append("<div class='poll-container'><form><div class='title'><p class='user'>Username</p><p class='title-text'>Poll title</p></div><label class='userPollLabel'><div class='inner-content'><input type='radio' name='polls' value='0'>First option</div></label><label class='userPollLabel'><div class='inner-content'><input type='radio' name='polls' value='1'>Second item</div></label></form></div>");


  $("input:radio").click(function() {

    var value = $(this).val();
    alert(value);

  });
});
//How do I make it so that when I click on one of the inputs, it only gives the value of the input that I'm clicking and not the value of all the inputs?

CSS:

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

button {
  position: absolute;
  top: 0;
  right: 2%;
  width: 25%;
  height: 10%;
}

.poll-container {
  border-style: solid;
}

我想要发生的是只返回一个值,但是当有多个轮询时,值 0 或 1 会多次返回。

4

1 回答 1

1

你所做的正是我在上面评论中描述的。每次单击该按钮时,您都在扫描页面以查找页面上的每个输入按钮,并将新的单击处理程序附加到每个按钮(那些已经具有单击处理程序的人在每次传递时都会获得另一个重复的处理程序)。因此,例如,在向页面添加 3 个表单后,第一组单选按钮已经附加了 3 次点击事件,这就是为什么除了最后添加的一组单选按钮之外,每组单选按钮都会收到多个警报。

解决方法是仅将单击事件附加到您正在添加的两个新单选按钮上,即那些尚未附加单击处理程序的单选按钮。因此,您必须像我在下面所做的那样确定您的选择器的范围。

这是我更改的代码的重要部分:

let newHtml = "<div>...radio buttons...</div>"; //removed for brevity
/*
  use "appendTo()" instead of "append()"
    appendTo() returns the newly appended element which is what we want for this
    append() returns the container the new element was appended to (not what we want here)
*/
let appended = $(newHtml).appendTo("#display-polls-container");

//then attach the click handler ONLY to the radio buttons
//found within the newly appended element
$(appended).find("input:radio").click(function() {
    alert($(this).val())
});

这里有一个工作示例 https://jsfiddle.net/wa172ztg/

于 2019-07-26T19:15:37.630 回答