将'event.target.id'作为String

时间:2013-11-26 15:19:36

标签: javascript jquery

以下脚本返回错误:

"Uncaught TypeError: Object Reg_8712 has no method 'indexof' 

Reg_8712是解雇该事件的单选按钮ID。

剧本:

$("input:radio").change(function (event) {            

            alert(event.target.id); // this works! it returns it as string.
            var eti =  event.target.id; // 'eti' gets the object and not the string.
            var n = eti.indexof("_"); // error! cannot indexof ('eti' is an object and not string)
            var fid = eti.substring(n);

如何将'eti'作为字符串?

2 个答案:

答案 0 :(得分:3)

如果某些内容确实不是字符串,最简单的转换方法是使用通用的.toString()方法:

var eti =  event.target.id.toString();
var n = eti.indexOf("_");

Simple test case来证明这一点。

答案 1 :(得分:0)

indexOf

的语法

string.indexOf(searchValue[, fromIndex])

      alert(event.target.id); // this works! it returns it as string.
        var eti =  event.target.id.toString(); // 'eti' gets the object and not the string.
        var n = eti.indexOf("_"); // error! cannot indexof ('eti' is an object and not string)
        var fid = eti.substring(n);

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf