MDL jQuery:标签将内容重叠到输入字段中

MDL jQuery:标签将内容重叠到输入字段中

问题描述:

我使用Firefox版本40.0.3/Chrome 45.0.2454.85,并且遇到以下问题:
如果我使用jQuery,placeholder/label会覆盖内容.

I use Firefox Version 40.0.3/Chrome 45.0.2454.85 and i have the following problem:
The placeholder/label overlaps the content, if i use jQuery.

Javascript:

$("#eventAddKurzLB").val("test");

HTML:

<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="eventAddKurzLB" />
    <label class="mdl-textfield__label" for="eventAddKurzLB">Kurzbezeichnung:</label>
    <span class="mdl-textfield__error">Es sind nur Zahlen, Buchstaben und Bindestriche erlaubt!</span>
</div>

示例:

实时示例:
https://jsfiddle.net/vutLb9ut/2/

问题不是jQuery,而是该组件没有意识到您所做的更改(对HTML元素进行编程更改不会意识到这一事实)触发事件),因此它不知道应该更改其外观.您可以通过在框中手动输入来进行测试;即使加载了jQuery,它也应该可以正常工作.

The problem isn't jQuery, but rather the fact that the component is unaware of the changes you're making (programmatic changes to an HTML element don't trigger events), so it doesn't know it should change its looks. You can test this by manually typing into the box; that should work correctly, even if jQuery is loaded.

您可以执行以下操作,使用元素的API来更改文本:

You can use the element's API for changing the text instead, by doing:

$("#my-textfield").get(0).MaterialTextfield.change('test');

(其中my-textfield是外部label元素),前提是该元素已完成升级.另一种选择是像您一样直接执行更改,但是会触发对元素的脏"检查:

(where my-textfield is the outer label element), provided the element is done upgrading. The other option is to perform the change directly, as you are doing, but triggering a "dirtiness" check on the element:

$("#my-textfield").get(0).MaterialTextfield.checkDirty();

希望这会有所帮助!