如何在不使用jquery的情况下使用字符计数来初始化textarea?

时间:2018-04-10 01:32:15

标签: javascript jquery html materialize

我不能仅使用HTML来显示MaterialiseCSS中的字符计数器。该网站示例在jQuery中实现。我不能在我的React项目中使用jQuery,所以我想知道是否有一种方法可以通过使用materializeCSS的JS来初始化具有字符数的MaterialiseCSS textarea?下面以materialiseCSS的JS中有一个可行的日期选择器为例,非常感谢!

Character Counter from MaterializeCSS website



< script src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js" > < /script> <
script >
  const datePicker = document.querySelector('.datepicker');
const datePickerInstance = M.Datepicker.init(datePicker);

//TODO:How to modify these two statements below to make textarea character counter workable by using materializecss' js, just like the "date-pick" one above? Cause materializecss says it doesn't require jQuery as a dependency.

const textNeedCount = document.querySelector('textarea #description');
const textNeedCountInstance = M.CharacterCounter(textNeedCount);

<
/script>
&#13;
<!-- CSS --><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"><!-- Compiled and minified CSS --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Parallax Template - Materialize</title>
</head>

<body>
  <header>
  </header>

  <main>
    <div class="row">
      <br>
      <form class="col s12 m6">
        <!--description-->
        <div class="row">
          <div class="input-field col s12">
            <textarea id="description" class="materialize-textarea" data-length="50"></textarea>
            <label for="description">描述</label>
          </div>
          <div class="input-field col s12 colorDataPicker">
            <i class="material-icons prefix">textsms</i>
            <input type="text" class="datepicker" id="date-pick">
            <label for="date-pick">生日</label>
          </div>
        </div>
      </form>

    </div>
  </main>
</body>

</html>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:0)

https://github.com/Dogfalo/materialize/issues/5730

你应该像这样初始化字符计数器:

var elems = document.querySelectorAll('.has-character-counter');
M.CharacterCounter.init(elems);

答案 1 :(得分:0)

为我工作:

abs(f(X)) < epsilon

答案 2 :(得分:0)

import React, {useEffect} from 'react';
import M from 'materialize-css';

useEffect(()=>{
  const elems = document.querySelectorAll('.counter');
  M.CharacterCounter.init(elems);
}, [])

// or, using class components:
componentDidMount() {
  const elems = document.querySelectorAll(".counter");
  M.CharacterCounter.init(elems);
}

答案 3 :(得分:-1)

const textNeedCountInstance = M.CharacterCounter(textNeedCount);

您获得的错误是TypeError: Cannot call a class as a function。这意味着这是一个类,需要使用关键字new实例化。

const textNeedCountInstance = new M.CharacterCounter(textNeedCount);

DEMO:https://jsfiddle.net/wwukaaab/