keyup功能不起作用

时间:2018-06-15 10:23:02

标签: javascript jquery

我在js中创建一个字符计数器,但是keyup事件不起作用???

$(document).ready(function() {
  function countingCharacter(element, maxCount) {
    var countLength = $('#' + element).val().length();
    alert(countLength);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea onkeyup="countingCharacter("storyOutline",100)" onkeypress="countingCharacter("storyOutline",100);" onkeydown="countingCharacter("storyOutline",100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>

5 个答案:

答案 0 :(得分:1)

为了避免与函数范围相关的任何问题并将JS代码与HTML分开,我将使用以下事件绑定:

databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        StateDetails stateDetails = dataSnapshot.getValue(StateDetails.class);
        methodThatDoesSomething(stateDetails); //Method call

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
});

private void methodThatDoesSomething(StateDetails stateDetails) {
    //Do what you need to do with your stateDetails object
}

答案 1 :(得分:1)

Newtonsoft.Json.JsonException: 'Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.'

onkeyup="countingCharacter("storyOutline",100)"将关闭并打开"storyOutline"

中的引号

你可以在双引号中使用单引号:

onkeyup

答案 2 :(得分:0)

您可以使用event.currentTarget.textLength

获取textarea长度

&#13;
&#13;
$(document).on("keyup", "#storyOutline", function (e) {
  console.log(e.currentTarget.textLength);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea  id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline" required></textarea>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script>
$(document).ready(function(){
    $("input").keyup(function(){
       alert("your pressed the key");
    });
});
</script>
</head>
<body>
Enter your name: <input type="text">
</body>
</html>

当您在文本字段上键入时,您将找到已键入的警报消息。

答案 4 :(得分:-1)

使用单引号向内联JavaScript函数添加参数,因此:

<textarea onkeyup="countingCharacter('storyOutline')" ... ></textarea>

而不是

<textarea onkeyup="countingCharacter("storyOutline")" ...></textarea>

实际上并不需要这些参数(您可以将maxCount保留在函数的范围内)。然后使用event.target访问目标(输入框元素)。选择其输入值及其长度。

这是一个有效的代码:

function countingCharacter(maxCount) {
  console.log($(event.target).val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea onkeyup="countingCharacter(100)" onkeypress="countingCharacter(100);" onkeydown="countingCharacter(100)" id="storyOutline" rows="5" class="form-control" name="labinput7" placeholder="Story Outline"
  required></textarea>

您不应该使用alert进行调试,而是使用console.log

相关问题