简体   繁体   English

更改DIV宽度JavaScript的名称

[英]change name of DIV width JavaScript

I am using following code: 我正在使用以下代码:

... 
<div id="divcontainer1">
    ...
    <div id="divcontainer2">
          ...
    </div>
</div>
...

Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3". 现在,我想稍后在Div“ divcontainer3”中更改“ divcontainer2”。

What is the right way to check is exist divcontainer2 and when true, change in divcontainer2 width javascript ? 什么是正确的方法来检查divcontainer2是否存在,如果为true,则更改divcontainer2 width javascript吗?

Thank you, Hardy 谢谢哈迪

It is probably not nest practice but you can do this by changing the .outterHTML of the element. 这可能不是嵌套实践,但是您可以通过更改元素的.outterHTML来实现。 You would likely want to improve on this but here is a quick example. 您可能需要对此进行改进,但这是一个简单的示例。 The last line checks if div 2 exists. 最后一行检查div 2是否存在。

        var div2 = document.getElementById("div2");
        var html = div2.outerHTML;
        var idx = html.indexOf(">");
        var newtag = html.substring(0, idx).replace("div2", "div3");
        div2.outerHTML = newtag + html.substring(idx, html.length - 1);
        var contents = document.getElementById("div3").innerHTML;


        alert(document.getElementById("div2") != undefined);

All you do is 所有你要做的就是

  1. get the element .outterHTML 获取元素.outterHTML
  2. get the substring representing the tag. 获取代表标签的子字符串。
  3. Replace the text that defines it 替换定义它的文本
  4. Set the .outterHTML tag to our new string 将.outterHTML标记设置为我们的新字符串

Now you have a newly named div that keeps all of its attributes, position in the parent and content. 现在,您有了一个新命名的div,它保留了其所有属性,在父级中的位置和内容。

The alert line is how you check for the existence of an object. 警报行是您检查对象是否存在的方式。

I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this 我不相信有一种“适当的”方法可以执行此操作,但是我会将divcontainer2的内容存储在变量中,然后执行类似的操作

var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";

Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works. 当然,这需要您将divcontainer2放入名为containerofdiv2的div containerofdiv2但它可以工作。

If using jQuery, this will do it: 如果使用jQuery,则可以这样做:

$('#divcontainer2').attr('id','divcontainer3');

But you shouldn't be changing IDs. 但是您不应该更改ID。 Use classes instead and then use the jQuery's toggleClass() function, like: 使用类代替,然后使用jQuery的toggleClass()函数,例如:

<div id="divcontainer1">
    ...
    <div id="divcontainer2" class="style1">
    ...
</div>

$('#divcontainer2').toggleClass("style1 style2");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM