【问题标题】:onclick in one element show another element in javascriptonclick 在一个元素中显示 javascript 中的另一个元素
【发布时间】:2015-09-03 06:07:34
【问题描述】:

我想点击加号,然后在每个步骤中显示下一个字段,但我的代码在第三步中不起作用。有没有什么方法可以无限时间地执行这些步骤?tnx

<html>
<head>
<script>
function showfield(){
document.getElementById("hiddenfield").style.display="block";
}
</script>
</head>

<body>
<div class="form-group" >
<div class="rightbox"> <label for='phone'>Phone1</label></div>
<input type="tel" value="" />
<div class="plus" onClick="showfield()">+</div>
</div>

<div class="form-group" style="display:none;" id="hiddenfield">
<div class="rightbox"><label for='phone'>Phone2</label></div>
 <input type="tel" value="" />
<div class="plus" onClick="showfield()">+</div></div>
</div>

<div class="form-group" style="display:none;" id="hiddenfield">
<div class="rightbox"><label for='phone'>Phone3</label></div>
 <input type="tel" value="" />
<div class="plus" onClick="showfield()">+</div></div>
</div>
</body>
</html>

【问题讨论】:

  • ids 必须是唯一的...
  • id 应该是唯一的

标签: javascript jquery forms css


【解决方案1】:

您可以为每个隐藏字段使用唯一 id,然后将当前 id 作为参数发送到您的函数。

function showfield(id) {
     document.getElementById(id).style.display="block";
}

另一个选项是 jquery:

$('.plus').on('click', function() {
    $(this).parent().next().show();
});

查看jsfiddle

【讨论】:

  • MerC kheyli mamno0n :)
【解决方案2】:

正如其他人所说,一个元素的 ID 必须是唯一的,您可以使用类对相似的元素进行分组。

你需要做的是显示第一个隐藏字段组,

function showfield() {
  var el = document.querySelector(".hiddenfield");
  if (el) {
    el.classList.remove('hiddenfield')
  }
}
.hiddenfield {
  display: none;
}
<div class="form-group">
  <div class="rightbox">
    <label for='phone1'>Phone1</label>
  </div>
  <input type="tel" value="" />
  <div class="plus" onClick="showfield()">+</div>
</div>

<div class="form-group hiddenfield">
  <div class="rightbox">
    <label for='phone2'>Phone2</label>
  </div>
  <input type="tel" value="" />
  <div class="plus" onClick="showfield()">+</div>
</div>

<div class="form-group hiddenfield">
  <div class="rightbox">
    <label for='phone3'>Phone3</label>
  </div>
  <input type="tel" value="" />
  <div class="plus" onClick="showfield()">+</div>
</div>

IE10+支持

【讨论】:

    【解决方案3】:

    由于您已标记 jquery,您可以取消所有这些(重复的 id)和 showField(),并在 doc load 中添加:

    $('.plus').on('click', function() {
        $(this).parent().next().show();
    });
    

    [编辑:哦,这是fiddle]

    但是,我不确定当单击第三个 + 时您希望发生什么,因为没有更多的 div 可以显示。

    【讨论】:

      【解决方案4】:

      Change id="hiddenfield"class="hiddenfield" 在所有 div 中并更改显示字段如下:-

      function showfield() {
          document.getElementsByClassName("hiddenfield").style.display="block";
      }
      

      注意:- 支持的浏览器 IE9+、Chrome 4+、FF3+。 http://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 2013-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多