简体   繁体   English

onchange for id 后,onclick 功能将不起作用

[英]onclick function won't work after onchange for id

When i give my input in the beginning an id, then my button works just fine with an onclick function.当我在开始时给我的输入一个 id 时,我的按钮就可以使用 onclick 功能正常工作。 But if i assign an id to my button with an onchange function my button won't react to the onclickfunction while the id is correct.但是,如果我使用 onchange 函数为我的按钮分配一个 id,当 id 正确时,我的按钮不会对 onclick 函数做出反应。 Can anyone help me with this.谁能帮我这个。

This works:这有效:

 <input type="button" class="ok" value="Execute" id="mercedes"/>
 <script>
 $('#mercedes').on('click', function(e){
 ......
 </script>

This doesn't work:这不起作用:

 <select id="abc" onchange="func()">
   <option  value="volvo" id="1">Volvo</option>
   <option value="saab" id="2">Saab</option>
   <option value="mercedes" id="3">Mercedes</option>
   <option value="audi" id="4">Audi</option>
 </select>
 <input type="button" class="ok" value="Execute"/>
 <script>
     function func() {
         var b = document.getElementById("abc");
         var a= b.options[b.selectedIndex].value;
         $('input.ok').attr('id', a);
      }
 </script>
 <script>
 $('#mercedes').on('click', function(e){
 ......
 </script>

When I select mercedes from the options my input will get the id mercedes, but the onclick function still doesn't work.当我从选项中选择 mercedes 时,我的输入将获得 id mercedes,但 onclick 功能仍然不起作用。

$('#mercedes').on('click', function(e){

This is happening when the page loads.这是在页面加载时发生的。 The element does not have an id yet.该元素还没有 id。 Inside the on change you need to attach the event once the id is set.一旦设置了 id,您需要在 on change 中附加事件。

function func() {
     var b = document.getElementById("abc");
     var a= b.options[b.selectedIndex].value;
     $('input.ok').attr('id', a);
     $('#' + a).on('click', function(e){
          // do something
     });
  }

Fiddle: http://jsfiddle.net/bt3dsrbx/小提琴: http : //jsfiddle.net/bt3dsrbx/

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

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