亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我想實現如下的功能,請問如何實現?

我想實現如下的功能,請問如何實現?

Cats萌萌 2022-11-03 13:09:00
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);}
查看完整描述

2 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

你犯了一個錯誤,$.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;
}
else
return 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>


查看完整回答
反對 回復 2022-11-08
?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

<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>


查看完整回答
反對 回復 2022-11-08
  • 2 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號