我需要为选择器的另一个元素获取属性名称
这是我的HTML代码



//I've tried this but it does not work or maybe there is something wrong
/* $(document).ready(function() {
  $('#btnadd').click(function() {
    alert($(this).attr('name'));
  });
}); */

function addval() {
  var btnini=$(this).attr("name");
  $("#txt"+btnini).show();
  $("#btn"+btnini).show();
  $(this).css("display","none");
}

<!-- I've tried this but it does not work or maybe there is something wrong
//<button type="button" id="btnadd" name="opsional">Tambahkan</button> -->

<input type="text" id="txt-opsional" style="display:none;" />
<button type="button" onClick="addval()" name="opsional">Tambahkan</button>
<button type="button" id="btn-opsional" style="display:none;">simpan</button>





当我单击按钮“ tambahkan”时,文本框id =“ txt-opsional”和按钮id =“ btn-opsional”将显示,因此按钮“ tambahkan”将隐藏

我希望有更好的建议
谢谢

最佳答案

由于您使用的是内联事件处理程序(不建议使用,特别是使用jQuery时,不建议这样做),因此您需要传递对clicked元素的引用,因此可以在内联事件处理程序中使用this来实现此目的,例如



//I've tried this but it does not work or maybe there is something wrong
/* $(document).ready(function() {
  $('#btnadd').click(function() {
    alert($(this).attr('name'));
  });
}); */

function addval(el) {
  var btnini = $(el).attr("name");
  $("#txt-" + btnini).show();//also need to add `-` to txt
  $("#btn-" + btnini).show();
  $(el).css("display", "none");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- I've tried this but it does not work or maybe there is something wrong
//<button type="button" id="btnadd" name="opsional">Tambahkan</button> -->

<input type="text" id="txt-opsional" style="display:none;" />
<button type="button" onClick="addval(this)" name="opsional">Tambahkan</button>
<button type="button" id="btn-opsional" style="display:none;">simpan</button>







使用jQuery处理程序



//I've tried this but it does not work or maybe there is something wrong
$(document).ready(function() {
  $('.addval').click(function() {
    var $this = $(this),
      btnini = $this.attr("name");
    $("#txt-" + btnini).show(); //also need to add `-` to txt
    $("#btn-" + btnini).show();
    $this.hide();
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- I've tried this but it does not work or maybe there is something wrong
//<button type="button" id="btnadd" name="opsional">Tambahkan</button> -->

<input type="text" id="txt-opsional" style="display:none;" />
<button type="button" class="addval" name="opsional">Tambahkan</button>
<button type="button" id="btn-opsional" style="display:none;">simpan</button>

关于javascript - 如何在函数javascript中自行获取属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31714792/

10-11 17:18