猿问

我想实现如下的功能,请问如何实现?

var $={};
$.G=function() {
var a=arguments[0];
var b=(arguments[1]==null)?false:true;
var c= typeof(a);
if(!b) {
switch (c) {
case "string" :
return document.getElementById(a);
break;
case "object" :
return a;
break;
}
} else {
if(c=="string") {
return document.getElementsByTagName(a);
} else {
return null;
}
}
}
$.G(str)获得对象,然后我想实现$.G(str).getValue() (这个函数可以返回innerHTML或者value值) 既然$.G(str)是一个对象 我就想扩展Object添加了Object.prototyp.getValue来实现但是 在ie下一直提示“对象不支持次属性或方法”
Object.prototyp.getValue=function(){
alert(this);
}

Cats萌萌
浏览 106回答 2
2回答

慕少森

你犯了一个错误,$.G(str)返回的是dom对象,getValue() 却是$.G下面的方法。改成这样就可以了<html><head><script type="text/javascript">var $ = {};$.G = function() {var a = arguments[0];var b = (arguments[1] == null) ? false : true;var c = typeof (a);if (!b) {switch (c) {case "string":a = document.getElementById(a);break;case "object":break;}} else {if (c == "string") {a = document.getElementsByTagName(a);} else {a = null;}}this.getValue = function() {if (a.tagName == "INPUT") {return a.value;}elsereturn a.innerText;}return this;}function getSelected(obj) {alert($.G(obj).getValue());}</script></head><body><div id="msg">dddddddd</div><input type="text" id="txt" value="inputvalue"/><input type="button" onclick="getSelected('txt')" value="取text" /><input type="button" onclick="getSelected('msg')" value="取div" /></body></html>

慕码人2483693

<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JavaScript 测试</title><script type="text/javascript">$ = {};$.G = function(a, b) {var obj = null;var c = typeof(a);if(b) {if(c == "string") obj = document.getElementsByTagName(a);} else {obj = (c == "object") ? a : document.getElementById(a);}return {getObject: function() {return obj;},getValue: function() {return obj ? obj.value : null;}}}</script></head><body><input type="text" id="text1" value="1" /><input type="button" id="button1" value="测试" onclick="alert($.G('text1').getValue());" /></body></html>
随时随地看视频慕课网APP

相关分类

Java
我要回答