admin管理员组文章数量:1291203
i have a button:
<button id="my-button" type="button" onclick="action()">press me</button>
i want to get the id of the button ("my-button"), in the "action" function.
i tried to get it with:
var id = $(this).id;
var id = $(this).attr('id');
i tried to send the object from the dom:
<button id="my-button" type="button" onclick="action(this)">press me</button>
and it didn't work...
how can i get the id?
i have a button:
<button id="my-button" type="button" onclick="action()">press me</button>
i want to get the id of the button ("my-button"), in the "action" function.
i tried to get it with:
var id = $(this).id;
var id = $(this).attr('id');
i tried to send the object from the dom:
<button id="my-button" type="button" onclick="action(this)">press me</button>
and it didn't work...
how can i get the id?
Share Improve this question asked Mar 23, 2016 at 8:05 johnnyjohnny 432 silver badges4 bronze badges4 Answers
Reset to default 6You need to accept the parameter
function action(elm) {
alert(elm.id)
}
<button id="my-button" type="button" onclick="action(this)">press me</button>
However, as you are using jquery I would remend you to bind events using it.
$(function() {
$('#my-button').on('click', function() {
alert(this.id);
});
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>
Set the onclick event in your jquery code, Right now what ever is doing is old style, and is deprecated in few browsers (many in mobile browsers).
So remove the binding's of onlclick event from your HTML element and add in jquery as shown below.
$(function() { //document ready event
$('#my-button').on('click',function() {
var id = $(this).attr('id');
alert(id);
});
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>
<button id="1" onClick="reply_click(this.id)">Button</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>
event.target gives the element associated with the event, click in your case.
$(".btn-send").click((e)=>{
$this = jQuery(e.target); // e.target gives element associated (targeted) with this event (click)
console.log($this.data('id')); // loging data id for demo purpose
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Send message" class="btn-send" data-id="40" />
本文标签: javascriptget the clicked element jquery with onclick functionStack Overflow
版权声明:本文标题:javascript - get the clicked element jquery with onclick function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741508065a2382439.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论