我需要获取选择器另一个元素的属性名称 这是我的 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 时),您需要传递对被点击元素的引用,您可以通过在内联事件中使用 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/