包含事件、if/else语句和表单的jQuery逻辑

包含事件、if/else语句和表单的jQuery逻辑,jquery,html,logic,Jquery,Html,Logic,对于一个有经验的开发人员来说,这可能是显而易见的,但我正在自学jQuery,我遇到了这个问题。假设我有一个id为“btn”的按钮,Html为“Msg 1” 我想在单击按钮时将Html更改为“Msg 2”。 这是我尝试过的方法,而且很有效。但是,如果按钮是表单的一部分,这种方法将不起作用。当按钮是表单的一部分时,有没有办法做到这一点 (function($) { var test = true; $('#btn').on('click',function() { if(

对于一个有经验的开发人员来说,这可能是显而易见的,但我正在自学jQuery,我遇到了这个问题。假设我有一个id为“btn”的按钮,Html为“Msg 1” 我想在单击按钮时将Html更改为“Msg 2”。 这是我尝试过的方法,而且很有效。但是,如果按钮是表单的一部分,这种方法将不起作用。当按钮是表单的一部分时,有没有办法做到这一点

(function($) {
   var test = true;
   $('#btn').on('click',function() {
        if(test == true) {
            test = false;
            $(this).html('Msg 2');
        } else {
            test = true;
            $(this).html('Msg 1');
        }
   }
})(jQuery);

下面是一些JSFIDLE代码,它满足您的要求:

将.html()更改为.val(),并添加了一个e.preventDefault(),以便表单在按下时不会刷新整个页面

HTML代码:

<html>
<head></head>
<body>
    <form>
        Press me &gt;&gt; <input type="submit" id="btn" value="Msg 1"/>
    </form>
</body>
</html>​

我没有完全理解你的问题,但你可以试试这个

$('#btn').live('click', function(event) 
    {

         $(this).val('Msg 2');
    });

上面的解决方案是正确的,但除非动态创建按钮,否则不需要使用“on”或不推荐使用的“live”

$('#btn').click(function(e) {
    e.preventDefault(); //.. prevent the button from submitting the form
    test = !test;
    $(this).text(test ? 'msg 1' : 'msg 2'); //.. no need to use .html if you're just switching text
});

注意:此解决方案假设您使用的是
,如果您使用的是
,则需要使用
$(this).val()
,而不是
$(this).text()

如果它是表单的一部分,则不应被“表单的一部分”所影响,您的意思是它还是仍然?
$('#btn').click(function(e) {
    e.preventDefault(); //.. prevent the button from submitting the form
    test = !test;
    $(this).text(test ? 'msg 1' : 'msg 2'); //.. no need to use .html if you're just switching text
});