我试图检索我在输入标记的onchange属性中写入的文本。
例如:
<input type="text" id="test1" name="test1" onchange="some_js_func();" />
我想检索onchange的值,即&#34; some_js_func();&#34;加载我的html页面。
我尝试使用以下方法来访问它,方法与使用getElementById()函数访问hmtl元素的任何值相同:
var myvar = document.getElementById("test1").change;
但是上面的代码返回undefined。
有没有办法只使用javascript而不是jQuery或其他客户端脚本语言将onchange的值作为字符串获取?
我只想要以下特定文字:&#34; some_js_func();&#34;
答案 0 :(得分:4)
你只需要这样做:
document.getElementById("test1").getAttribute("onchange");
getAttribute()
方法将获取元素的属性值。
答案 1 :(得分:0)
只需使用.getAttribute()
:
//Out input element:
var myElem = document.getElementById("test1");
//Here, the appended text node has the same value as the string inputted into the onchange attribute in the HTML:
document.body.appendChild(document.createTextNode(myElem.getAttribute("onchange")));
&#13;
<input type="text" id="test1" name="test1" onchange="some_js_func();">
&#13;