简体   繁体   English

jQuery如何仅选择.clicked DOM元素

[英]Jquery how can I select only the .clicked DOM Element

I have a list with buttons. 我有一个带有按钮的列表。 All have the same class. 所有人都有同一个班级。 How would I be able to select only the DOM element that was clicked using jQuery? 我如何才能仅选择使用jQuery单击的DOM元素?

Say I wanted to call .fadeOut() on only the clicked button and leave the remaining buttons as they are... 假设我只想在单击的按钮上调用.fadeOut() ,而将其余按钮保持原样...

HTML: HTML:

<ul>
    <li><button class="sidebutton" >click Me1!</button></li>
    <li><button class="sidebutton" >click Me2!</button></li>
    <li><button class="sidebutton" >click Me3!</button></li>
    <li><button class="sidebutton" >click Me4!</button></li>
</ul>

try this: 尝试这个:

$('.yourclass').click(function () {
    $(this).fadeOut(); //$(this) is the clicked button
})
$("button").click(function(){
    $(this).fadeOut(); //this referes current clicked button
});

Two ways you could do this: 您可以通过两种方式执行此操作:

1. Assign an event handlers to each button: 1.为每个按钮分配一个事件处理程序:

$('.sidebutton').on('click', function () {
    $(this).fadeOut();
});

2. Assign one event handler to the <ul> and let the event propagate up: 2.<ul>分配一个事件处理程序,并使事件向上传播:

$('ul').on('click', '.sidebutton', function () {
    $(this).fadeOut();
});

Pls try this: 请尝试一下:

<html>
<head>
    <title>Helper</title>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
    <ul>
        <li><button>Click me!</button></li>
        <li><button>Click me!</button></li>
        <li><button>Click me!</button></li>
        <li><button>Click me!</button></li>
    </ul>
</body>
<script type="text/javascript">
    (function(){
        $('li button').on('click', function(){
            $(this).fadeOut("slow", function(){
                console.log('Completed!');
            })
        })
    })();


</script>       
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM