简体   繁体   English

jQuery-为什么这样不起作用?

[英]Jquery - why isn't this working?

Can someone tell me why the code below doesn't work. 有人可以告诉我为什么下面的代码不起作用。 I think my theory is sound, I am just missing some vital component. 我认为我的理论是正确的,我只是缺少一些重要组成部分。

'#tweet' is the id assigned to the form submit button. “ #tweet”是分配给表单提交按钮的ID。 I want it to check whether the input has less than 141 characters, if it doesn't, alert the user and do not submit the form. 我希望它检查输入的字符数是否少于141个,如果不是,请提醒用户,不要提交表单。

Currently it does nothing. 目前它什么都不做。

    $('#tweet').click(function() {
   if ($('.message').val().length > 140) {
    alert('Your message much be less than or exactly 140 characters');
    return false;
   }
  });

Put the above code like this 这样放置上面的代码

<script type="text/javascript">
$(function(){
  $('#tweet').click(function() {
    if ($('.message').val().length > 140) {
     alert('Your message much be less than or exactly 140 characters');
     return false;
    }
  });
});
</script>

in the section of your html after including jQuery library file. 包括jQuery库文件后的HTML部分中。 As event handlers are attached after the dom is ready. 在dom准备好后附加事件处理程序。

it may be possible, that your .message hits more elements! 您的.message可能会击中更多元素!

$(document).ready(function() {
    $('#tweet').click(function(e) {
        var success = true;
        $('.message').each(function() {
            if ($(this).val().length > 140) {
                alert('Your message much be less than or exactly 140 characters');
                success = false;
            }
        });
        if (!succeess) {
            e.preventDefault();
        }
        return success;
    });
});

you should attach your behaviour to the form submit event: 您应该将您的行为附加到表单提交事件:

 $('form').bind('submit',function() {
   if ($('.message').val().length > 140) {
    alert('Your message much be less than or exactly 140 characters');
    return false;
   }
  });

you probably want to prevent the default action instead of returning false 您可能想阻止默认操作,而不是返回false

$('#tweet').click(function( e ) {
    if ($('.message').val().length > 140) {
        alert('Your message much be less than or exactly 140 characters');
        e.preventDefault();
    }
});

For completeness, if your preventing default, you should probably go the following extra distance: 为了完整起见,如果您要防止出现默认值,则可能应该走以下距离:

function stopEvent(event) {
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

There's mroe info on this in my answer to the following question: jQuery form submission. 我对以下问题的回答中有关于mroe的信息: jQuery表单提交。 Stopping page refresh only works in newest browsers 停止页面刷新仅在最新的浏览器中有效

该ID应该是tweet而不是#tweet

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

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