Dynamically set js attributes and js attributes
Objective: To use variables for js attribute names
For example, when a js object is assigned to the object property, you can use the following method:
var object;
object.prop1 = "value1";
object.prop2 = "value2";
You can also use the following method:
object.push({prop1:"value1"});
object.push({prop2:"value2"});Here, prop1 is the property name, which can be used directly or enclosed by quotation marks, for example:
object.push({"<span style="font-family: Arial, Helvetica, sans-serif;">prop1</span>":"value1"});The expression has the same meaning. That is to say, prop1 can only be recognized as a constant, even if it is a variable, it is useless. For example:
var prop1 = "prop2";
object.push({prop1:"<span style="font-family: Arial, Helvetica, sans-serif;">value1</span>"});
In this way, what will happen when you access prop2 through object? For example:
alert(<span style="font-family: Arial, Helvetica, sans-serif;">object.prop2) </span>
You do not need to ask, of course, it is undefined, but the access to object. prop1 is "value1"
The reason has already been said, no matter the quotation marks are added, the attribute will be treated as a constant. Another example is as follows:
var arr=[];arr['js']='jquery';arr['css']='oocss';var obj={};for(var i in arr){ obj.i=arr[i];}alert(obj.js);
Do not guess what alert will print?
Of course it is undefined.
Let's guess, what will alert (obj. I) print?
Of course it's oocss. Why? Because obj only has one attribute I and uses two loops, the previous one is overwritten by the following one.
If you need to add attributes dynamically, that is to say, the attributes must also be a variable. In the code above, alert (obj. js) is not undefined, but jquery. How can we modify the attributes?
var arr=[];arr['js']='jquery';arr['css']='oocss';var obj={};for(var i in arr){ obj[i]=arr[i];}alert(obj.js);
That's easy! Treat object obj as an array. It supports assigning attributes and attribute values to objects using methods similar to subscripts. However, objects are still objects and obj. length does not exist.
JS dynamically sets the ID attribute for DIV
I don't know what you want to do.
<Script>
Var objs = document. getElementById ("iproduct"). getElementsByTagName ("div ");
For (var I = 0; I <objs. length; I ++)
{
Objs [I]. id = "......";
}
</Script>
How to Set dynamic tr attributes in js
The two insert Methods return the inserted objects. You can directly operate on these two objects, for example:
Var tr = table. insertRow ();
Var td = tr. insertCell ();
Tr. setAttribute ('align ', 'center');' can be directly used without setAttribute.
Tr. setAttribute ('bgcolor', '# FF0000 ')
Td. width = 100; 'directly assigns values to attributes.
If you have any questions, please check your answers.