Javascript字符串不是一个函数

Mat*_*ght 1 javascript select onchange undefined

我正在尝试onChangeselect元素上添加事件.html看起来像这样:

<select name="to" onChange="if(type(this.selectedIndex) != undefined){ alert('hello'); }">
    <option value="newsletter">Alle nieuwsbrief-abonnees</option>
    <option value="customer_all">Alle klanten</option>
    <option value="customer_group">Klantengroep</option>
    <option value="customer">Klanten</option>
    <option value="affiliate_all">Alle affiliates</option>
    <option value="affiliate">Affiliates</option>
    <option value="product">Producten</option>
    <option value="marketing">Alle Marketing Abbonnees</option>
    <option value="marketing_all">Alle Marketing</option>
    <option value="subscriber">Alle Nieuwsbrief Abbonnees &amp; Marketing Abbonnees</option>
    <option value="all">Alle Klanten &amp; Marketing</option>
    <option value="old_brian">Oude lijst Brian</option>
    <option value="old_dunamis">Oude lijst Dunamis</option>
    <option value="old_frohlich">Oude lijst Frohlich</option>
    <option value="old_gaithers">Oude lijst Gaithers</option>
    <option value="old_gospel7">Oude lijst Gospel7</option>
    <option value="old_lifeshop">Oude lijst Lifeshop</option>
    <option value="old_meyer">Oude lijst Meyer</option>
    <option value="old_opwekking">Oude lijst Opwekking</option>
    <option value="old_pelgrim_kerken">Oude lijst Perlgim Kerken</option>
    <option value="old_pelgrim_klanten">Oude lijst Pelgrim Klanten</option>
    <option value="old_pelgrim_pers">Oude lijst Pelgrim Pers</option>
    <option value="old_pelgrim_scholen">Oude lijst Pelgrim Scholen</option>
    <option value="old_test">Oude lijsten test</option>
</select>
Run Code Online (Sandbox Code Playgroud)

这是它的JSFIDDLE

onchange脚本来自stackoverflow的答案:是否有针对HTML的onSelect事件或等效事件?

但是我收到以下错误:

Uncaught TypeError: string is not a function 
Run Code Online (Sandbox Code Playgroud)

我很笨,问题是什么?你不能在onChange事件中做一个if语句吗?或者是别的什么?

T.J*_*der 6

type不是内置函数.typeof但是,它是一个运营商,可能是你想要的; 它返回一个字符串:

if (typeof this.selectedIndex !== "undefined") // But see below
Run Code Online (Sandbox Code Playgroud)

但请注意,selectedIndex从不undefinedselect元素上.它可以是-1,表示没有选择,但没有undefined.所以:

if (this.selectedIndex !== -1)
Run Code Online (Sandbox Code Playgroud)

关于错误:我的猜测是你有一个名为的全局变量type,它包含一个字符串.这会给你错误TypeError: string is not a function.