2

In my javascript code, I'm creating an <object> like so:

var myObject = document.createElement('object');

Then, I to add some parameters to this object, so that these are reflected in my html.

I can do it like this, but after adding more and more paremeters, this code gets really messy and repetitive.

var param1 = document.createElement('param');
param.setAttribute('name', 'myName');
param.setAttribute('value', 'myValue');
myObject.appendChild(param1);

Is there a better way to create an and add parameters to this object?

If it makes any difference, this is an activeX control object.

Thanks!


Try using media queries, instead. Look at http://cssmediaqueries.com/

4

4 回答 4

0

像这样的事情会做到这一点

function addParams(obj, paramsObj){

  for(vals in paramsObj)
  {
     obj.setAttribute(vals, paramsObj[vals])
  }
}

var myObject = document.createElement('object');
var paramsObj = {
                  "value":"myValue"
                  "name":"myName" 
                };

addParams(myObject, paramsObj);
于 2012-09-14T14:21:21.520 回答
0

有多种添加属性的方法

1

param1.name=myName;

2

param1[name]=myName;

并且您可以通过使用循环检查该属性是否存在于对象中,for in并确保您使用hasProperty它来将其限制为对象自己的属性。

于 2012-09-14T14:16:21.520 回答
0

您可以将该代码放入一个addParameters函数中,该函数接受一个对象并使用for in循环来添加对象中的所有属性。

于 2012-09-14T14:11:07.993 回答
0

有多种令人兴奋的自助餐可供您选择:

elem.id = 'NewId';
elem.value = 'NewValue';//etc...
elem.style.width = '100%';

或者,如果您只创建 1 个对象:

elem = '<div id="Foo" class="bar blackBlock andSomeOtherClass">InnerText or innerHTML go here</div>';

在大多数情况下,这甚至比手动创建它还要快... :)

如果没有,这是我不时使用的一个小功能:

function createAssign(elem,attr)
{
    var i;
    elem = (typeof elem === 'object' ? elem : document.createElement(elem));
    if (typeof attr !== 'object')
    {
        return elem;
    }
    for (i in attr)
    {
        if (attr.hasOwnProperty(i))
        {
            elem[i] = (typeof attr[i] === 'object' ? createAssign(elem[i],attr[i]) : attr[i]);
        }
    }
    if (this !== window && this.appendChild)
    {
        this.appendChild(elem);
        return true;
    }
    return elem;
}
var el = createAssign('div',{id:'Foo',innerHTML:'bar',style:{width:'100%'}});
//or append directly:
createAssign.apply(document.body,['div',{id:'Foo',innerHTML:'bar',style:{width:'100%'}}]);
于 2012-09-14T14:18:08.930 回答