获取'event.target.id'作为字符串

Get 'event.target.id' as String

本文关键字:字符串 event 获取 target id      更新时间:2023-11-12

以下脚本返回错误:

"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("_");

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

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