Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
977 views
in Technique[技术] by (71.8m points)

dom - Set custom attribute using JavaScript

I am using The DynaTree (https://code.google.com/p/dynatree) but I am having some problems and hoping someone can help..

I am displaying the tree on the page like below:

<div id="tree">
        <ul>
            <li class="folder">Outputs
                <ul>
                    <li id="item1" data="icon: 'base.gif', url: 'page1.htm', target: 'AccessPage'">Item 1 Title
                    <li id="item2" data="icon: 'base.gif', url: 'page2.htm', target: 'AccessPage'">Item 2 Title
                    <li id="item3" data="icon: 'base.gif', url: 'page3.htm', target: 'AccessPage'">Item 3 Title
                    <li id="item4" data="icon: 'base.gif', url: 'page4.htm', target: 'AccessPage'">Item 4 Title
                </ul>
        </ul>
    </div>

However I am trying to change the icon on a item no matter if it's selected or not only using JavaScript.

the new icon I want to use is base2.gif

I have tried using the following but it don't seem to work:

document.getElementById('item1').data = "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'";

anyone know what I might be doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the setAttribute method:

document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");

But you really should be using data followed with a dash and with its property, like:

<li ... data-icon="base.gif" ...>

And to do it in JS use the dataset property:

document.getElementById('item1').dataset.icon = "base.gif";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...