jQuery - 显示和隐藏按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15067646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:18:35  来源:igfitidea点击:

jQuery - Show and hide button

jqueryhideshow

提问by David

I have written a script that shows a submit button when clicking inside an input area. And when clicking outside the input, the button should be hidden. There are several areas and buttons, therefore I have assigned a unique ID to every button and area.

我编写了一个脚本,在输入区域内单击时显示提交按钮。当在输入之外点击时,按钮应该被隐藏。有几个区域和按钮,因此我为每个按钮和区域分配了一个唯一的 ID。

The problem is: When I click the area, the button shows. But when clicking outside, nothing happens. The script works if I only have one button and area, but when assigning IDs, it stops working...

问题是:当我单击该区域时,按钮显示。但是当点击外面时,什么也没有发生。如果我只有一个按钮和区域,脚本就可以工作,但是在分配 ID 时,它停止工作......

$(".textarea").click(function(e) {
    var cid = $(this).attr('rel');

    $("#submit" + cid).show();
    e.stopPropagation();
});

$(document).click(function() {
    $("#submit" + cid).hide();
});

采纳答案by K D

$(".textarea").click(function(e) {
    var cid = $(this).attr('rel');

    $("#submit" + cid).show();
    e.stopPropagation();
});

$(document).click(function() {
    //add logic to hide all submit buttons by assigning common class to all
});

回答by Kami

The variable cidis declared in the anonymous text area click handler. So, when the other function is called as a result of a click, it does not have a value.

该变量cid在匿名文本区域单击处理程序中声明。因此,当另一个函数因单击而被调用时,它没有值。

Change you hide function to something independent of cidlike this

将您的隐藏功能更改为独立于cid这样的功能

$(document).click(function() {
    $("button[id*=submit]").hide();
});

The id*=submitsection will look for all buttons that have submitin the idand hide them. This will circumvent the need to track cid. If you have other buttons with submitin the id that you do not want to hide, then selecting based on a class or changing the id format will be required.

id*=submit节将寻找具有所有按钮submitid和隐藏它们。这将避免跟踪的需要cid。如果您submit不想隐藏 id 中的其他按钮,则需要根据类进行选择或更改 id 格式。