如何删除自动对焦属性

时间:2018-08-07 03:19:22

标签: javascript jquery html

我想通过onfoucus事件获得更多输入字段

function new_option() {
  var tot_opt = parseInt($('#tot_opt').val());
  $('#otp' + tot_opt).unbind('onfocus', "new_option");
  tot_opt++;
  $('#tot_opt').val(tot_opt);
  var opt = "<br><input onfocus='new_option()' id='otp" + tot_opt + "' placeholder='Options" + tot_opt + "' type='text' name='options' class='form-control'>"
  $('#new_opt').append(opt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered">
  <tr>
    <th colspan="2">Create Voter Pool</th>
  </tr>
  <tr>
    <th>Question</th>
    <th><textarea name="question" class="form-control">
				
			</textarea></th>
  </tr>
  <tr>
    <th>Options</th>
    <td>
      <input type="text" placeholder="Options1" id="opt1" class="form-control" name="options"><br>
      <input type="text" onfocus="new_option()" id="opt2" placeholder="Options2" class="form-control" name="options">
      <span id="new_opt"></span>
      <input type="hidden" id="tot_opt" value="2">
    </td>
  </tr>
</table>

我只希望onfocus属性出现在最后一个输入上,并希望从剩余的内容中删除onfoucs属性

1 个答案:

答案 0 :(得分:1)

在添加新输入之前,您可以从所有其他输入中删除onfocus属性。

以下内容将查询具有onfocus属性的输入,并循环遍历每个元素以删除该属性。然后,我在最后一个输入后面附加onfocus属性。这样可以确保只有最后一个输入才可以添加另一个输入。

function new_option() {
  var tot_opt = parseInt($('#tot_opt').val());
  $('#otp' + tot_opt).unbind('onfocus', "new_option");
  tot_opt++;
  $('#tot_opt').val(tot_opt);
  var opt = "<br><input onfocus='new_option()' id='otp" + tot_opt + "' placeholder='Options" + tot_opt + "' type='text' name='options' class='form-control'>"
  // remove onfocus from all previous inputs (that have the onfocus attribute)
  document.querySelectorAll("input[onfocus]").forEach(function(element, index) {
    element.removeAttribute("onfocus");
  });

  $('#new_opt').append(opt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered">
  <tr>
    <th colspan="2">Create Voter Pool</th>
  </tr>
  <tr>
    <th>Question</th>
    <th><textarea name="question" class="form-control"></textarea></th>
  </tr>
  <tr>
    <th>Options</th>
    <td>
      <input type="text" placeholder="Options1" id="opt1" class="form-control" name="options"> <br>
      <input type="text" onfocus="new_option()" id="opt2" placeholder="Options2" class="form-control" name="options">
      <span id="new_opt"></span>
      <input type="hidden" id="tot_opt" value="2">
    </td>
  </tr>
</table>