我正在尝试制作一个包含2个按钮执行不同操作的网页。当我单击一个按钮时,它正在执行这两个功能,但是我希望它仅执行一个功能。

任务3.1:200x200绿框div:

<button>Remove</button>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("div").remove();
        });
    });
    <br/>
</script>

<button>Animate</button>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("div").animate({ left:'300px' });
        });
    });
</script>

<div style="
    width: 200px;
    height: 200px;
    padding: 25px;
    border: 25px solid green;
    margin: 25px;
    position: absolute;">
</div>

最佳答案

选择器"button"匹配当时文档中的每个按钮。当选择器匹配多个元素时,$.fn.click方法实际上循环遍历该结果集合,并绑定到每个匹配的元素。

如果您只想匹配特定的元素,则需要将它们与其他匹配的元素区分开。如果给他们一个唯一的ID,最常用的方法之一:

<button id="remove">Remove</button>
<button id="animate">Animate</button>


然后根据您的脚本专门针对那些对象:

$("#remove").click(function remove () {
    $("div").remove(); // This removes every div from the document
});

$("#animate").click(function animate () {
    $("div").animate({ left: 300 }); // Animates the left property of every div
});

关于javascript - 在jQuery中声明多个按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27336513/

10-12 07:01