0

我有一个文本区域和一个提交按钮。当用户在 textarea 之外单击时,将运行一个脚本,如果 textarea 中没有任何内容,它会隐藏提交按钮。但是,如果您在文本区域之外单击,我不希望这样,因为当您单击提交按钮时,它会运行该操作并隐藏该按钮。它不应该。所以我需要检测用户何时在 textarea 的包装 div 之外单击并提交按钮并运行脚本。

 <div class="wrapper">
     <textarea class="textarea"></textarea>
     <input type="submit" class="submit" value="submit"/>
 </div>
4

2 回答 2

1

检查事件的“目标”属性,它将告诉您实际单击了哪个元素。然后,您可以执行条件语句以确保提交按钮没有调度事件。

jQuery 文档:http ://api.jquery.com/event.target/

Mozilla 文档:https ://developer.mozilla.org/en-US/docs/DOM/event.target

于 2012-08-20T03:24:06.157 回答
0

Something like this:

$(document).ready(function() {
    var $text = $("textarea.textarea"),
        $btn = $("input.submit");
    $(document).click(function(e) {
        if (!$text.is(e.target) && !$btn.is(e.target) && $text.val() == "")
            $btn.hide();
        else
            $btn.show();
    });
});

That is, bearing in mind that click events bubble up to the document but you can still determine the originally clicked element with event.target, on any click event that the document receives test whether the click was somewhere other than the textarea or button, and if so and the textarea is empty hide the button, otherwise show it.

Demo: http://jsfiddle.net/HpmDF/

Note that using classes to identify individual controls isn't the best plan, that's what id is for. If there can be more than one textarea and associated button you'll need a different solution.

P.S. Note also that you asked explicitly about "clicks" and that's what I've provided, but you need to allow for the user tabbing out via the keyboard...

于 2012-08-20T03:30:09.440 回答