将’event.target.id’作为String

以下脚本返回错误:

"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’作为字符串?

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

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

简单的测试用例来certificate这一点。

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