简体   繁体   English

事件侦听器仅在第二次单击后才能正确触发

[英]Event listener only triggers correctly after second click

I have an event listener that listens for clicks on a group of radio buttons, then passes the checked value to a function. 我有一个事件侦听器,它侦听一组单选按钮上的单击,然后将检查后的值传递给函数。

I then output the checked value to the web console whenever a radio button is selected, but this only works if the radio button is clicked twice after page load. 然后,无论何时选择单选按钮,我都会将检查后的值输出到Web控制台,但这仅在页面加载后单击两次单选按钮时有效。

 var t1q1El = document.getElementById("t1q1"); function question_1() { $(function(){ $("#t1q1").one('click',function(){ var t1q1UserInput = $("input[name=t1q1]:checked").val(); questionsData['question_1']['input'] = t1q1UserInput; assessPoints('question_1', t1q1UserInput); }); }); } t1q1El.addEventListener("click", question_1); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <fieldset id="t1q1"> <label>Strongly Agree <input type="radio" value="strongly-agree" name="t1q1"> </label> <label>Agree <input type="radio" value="agree" name="t1q1"> </label> <label>No Stance <input type="radio" value="no-stance" name="t1q1"> </label> <label>Disagree <input type="radio" value="disagree" name="t1q1"> </label> </fieldset> </form> 

On the second click, the value is passed to the web console immediately after clicking. 第二次单击时,该值将在单击后立即传递到Web控制台。 All consecutive clicks function as expected. 所有连续的点击均按预期运行。 Why doesn't the first click trigger anything? 为什么第一次点击不会触发任何东西?

I'm still learning JS so please excuse/correct any bad practices.. 我仍在学习JS,因此请原谅/纠正任何不良做法。

Here is what happening: 这是发生了什么:

1) t1q1El.addEventListener("click", question_1); 1) t1q1El.addEventListener("click", question_1); You assign a function to t1q1El . 您将一个函数分配给t1q1El Basically you are saying do question_1 when t1q1El is clicked. 基本上,您说的是单击t1q1El时执行“ question_1

2) Click 1. We do question_1 which is assigning a click event to t1qE1 . 2)单击1。我们执行question_1 ,该事件正在将点击事件分配给t1qE1 Now t1qE1 has 2 events. 现在t1qE1有2个事件。

3) Click 2. Doing question_1 (which is assigning another click event on itself) and executing that click. 3)单击2。执行question_1 _1(这将为其自身分配另一个click事件)并执行该click。

Solution is simple to just assign a click event: 仅分配click事件的解决方案很简单:

 $(function(){
        $("#t1q1").one('click',function(){
            var t1q1UserInput = $("input[name=t1q1]:checked").val();
            questionsData['question_1']['input'] = t1q1UserInput;
            assessPoints('question_1', t1q1UserInput);
        });
});

BTW one() will execute only once, if you need to keep the event after first executions use on() BTW one()仅执行一次,如果您需要在第一次执行后使用on()保留事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM