動態設定js的屬性,動態設定js屬性

來源:互聯網
上載者:User

動態設定js的屬性,動態設定js屬性

目標:js的屬性名稱可以使用變數

舉例:js對象object,當賦給該對象屬性的時候可以採用以下方式

var object;
object.prop1 = "value1";
object.prop2 = "value2";
也可以採用如下方式:

object.push({prop1:"value1"});
object.push({prop2:"value2"});
在這裡prop1 作為屬性名稱,可以直接用,也可以加上引號,比如:

object.push({"<span style="font-family: Arial, Helvetica, sans-serif;">prop1</span>":"value1"});
表達的含義都是一樣的,也就是說,prop1隻能作為常量被識別,即使它是個變數也沒用,例如:

var prop1 = "prop2";
object.push({prop1:"<span style="font-family: Arial, Helvetica, sans-serif;">value1</span>"});

這樣通過object訪問prop2會出現什麼情況呢?比如:

alert(<span style="font-family: Arial, Helvetica, sans-serif;">object.prop2) </span>
不用問,當然是undefined,而訪問object.prop1卻是"value1"

原因已經說過了,無論加不加引號,屬性一律當成常量對待.再舉一個例子:

var arr=[];arr['js']='jquery';arr['css']='oocss';var obj={};for(var i in arr){     obj.i=arr[i];}alert(obj.js);

讀者不放猜一下alert會列印什麼?

當然是undefined.

大家再猜一下,如果alert(obj.i)會列印什麼?

當然是oocss,為什麼?因為obj現在只有一個屬性i,而且通過兩次迴圈,obj.i前面的被後面的覆蓋掉.

如果有需求,需要動態添加屬性,也就是說,屬性也必須是一個變數才行,如上例代碼,alert(obj.js)不是undefined,而是jquery,該如何修改呢?

var arr=[];arr['js']='jquery';arr['css']='oocss';var obj={};for(var i in arr){     obj[i]=arr[i];}alert(obj.js);

就是那麼簡單!把對象obj當成一個數組來對待,它支援使用類似於下標形式的方法來把屬性和屬性值賦給對象.但是,對象依然是對象,obj.length是不存在的.



JS為DIV動態設定ID屬性

雖然不知道你要幹嘛
<script>
var objs=document.getElementById("iproduct").getElementsByTagName("div");
for(var i=0;i<objs.length;i++)
{
objs[i].id="......";
}
</script>
 
js中怎設定動態tr的屬性

兩個insert方法返回的就是被插入的對象,直接操作這兩個對象就行了,比如:
var tr = table.insertRow();
var td = tr.insertCell();
tr.setAttribute('align','center'); '不用setAttribute而直接使用屬性也可以.
tr.setAttribute('bgcolor','#FF0000')
td.width=100; '直接對屬性賦值的作法.
如果還有問題歡迎追問,問題解決請及時選為滿意回答,謝謝.
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.