在TypeScript中使用jQuery $前缀

时间:2015-07-07 11:41:34

标签: jquery typescript

我正在尝试将html输入控件转换为typescript中的HTMLInputElement。试图通过普通的简写jQuery方法访问输入控件,

e.g. <HTMLInputElement> $("#CompareToControl")

导致一个波浪形的红线错误“JQuery和类型HTMLInputElement都不能彼此分配。

有没有办法让这个工作,或者我们被迫使用旧的长手方式来引用控件,例如。

 <HTMLInputElement> document.getElementById("CompareToControl");

1 个答案:

答案 0 :(得分:3)

这是因为$(expn)不返回DOM元素,而是返回JQuery对象,并且它们不能彼此分配。因此,您需要将jquery对象中的DOM元素设置为HTMLInputElement类型。即

<HTMLInputElement> $("#CompareToControl")[0]

您正在使用的$(expn)的输入声明如下。 ($的类型为JQueryStatic)

interface JQueryStatic {
     /**
     * Accepts a string containing a CSS selector which is then used to match a set of elements.
     *
     * @param selector A string containing a selector expression
     * @param context A DOM Element, Document, or jQuery to use as context
     */
    (selector: string, context?: JQuery): JQuery;
}