javascript - 如何去除自动对焦属性

标签 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 属性,并且想从 remain 中删除 onfocus 属性

最佳答案

在添加新输入之前,您可以从所有其他输入中删除 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>

关于javascript - 如何去除自动对焦属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718350/

相关文章:

javascript - 如何使用打开 vue-js 模式的可点击组件在 vue-js 中创建 TreeView ?

javascript - Android上的Javascript音频播放已静音

javascript - 在同一个导航栏中有两个下拉菜单

javascript - JQuery +thumbs_up gem 渲染投票数?

javascript - 如何在站点加载后使输入字段聚焦?

javascript - Jquery 以编程方式更改 <p> 文本

php - 从ajax调用输出图像的最快方法

javascript - 在 Vue 中使用 Axios 将查询参数传递给 URL 的最佳方式?

javascript - 从按键上的文本区域获取最后一行

javascript - 营业时间 - DIV 取决于星期几和小时