使用onclick函数获取点击的元素jquery
get the clicked element jquery with onclick function
我有一个按钮:
<button id="my-button" type="button" onclick="action()">press me</button>
我想在"action"函数中获取按钮("my button")的id。
我试着用
var id = $(this).id;
var id = $(this).attr('id');
我试图从dom发送对象:
<button id="my-button" type="button" onclick="action(this)">press me</button>
但它没有起作用。。。
我怎样才能拿到身份证?
您需要接受参数
function action(elm) {
alert(elm.id)
}
<button id="my-button" type="button" onclick="action(this)">press me</button>
但是,由于您正在使用jquery,我建议您使用它绑定事件
$(function() {
$('#my-button').on('click', function() {
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="my-button" type="button">press me</button>
在jquery代码中设置onclick事件,现在所做的都是老式的,在少数浏览器中不推荐使用(许多在移动浏览器中)。
因此,从HTML元素中删除onlick事件的绑定,并添加jquery,如下所示。
$(function() { //document ready event
$('#my-button').on('click',function() {
var id = $(this).attr('id');
alert(id);
});
});
<script src="https://ajax.googleapis.com/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提供与事件相关联的元素,在您的情况下单击。
$(".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.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Send message" class="btn-send" data-id="40" />
相关文章:
- 可以't附加html元素jquery
- 循环遍历元素jquery选择器
- 在ajax加载的元素jquery上包含现有的jquery函数
- 如何删除元素列表中的类并添加到另一个元素 Jquery.
- 获取单击的类元素 jQuery 的名称值
- 获取上一个元素 jQuery 的内容
- 根据另一个元素的更改获取一个元素(jquery)
- 区分不同的可拖放元素(jQuery 拖放)
- 除了最后一个<td>元素-Jquery
- 获取子元素jQuery的单选按钮值
- 捕获元素jquery外部的mousedown事件
- .append到非DOM元素jQuery
- 获取其父元素的精确子元素.Jquery
- 获取重复结构中的特定元素jquery
- 捕获隐藏输入元素jQuery的值
- 使用onclick函数获取点击的元素jquery
- 返回父元素 jquery 中的输入值
- 按属性查找元素 jQuery
- 选择元素 jQuery
- 按子元素 - jQuery 的数据 ID 对 li 进行排序