使用JavaScript设置数据属性 [英] Set data attribute using JavaScript

查看:90
本文介绍了使用JavaScript设置数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DynaTree(https://code.google.com/p/dynatree),但我遇到一些问题,希望有人能够帮助..

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>

但是,我正在尝试更改项目上的图标,无论是选择还是不仅使用 JavaScript

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

我要使用的新图标是base2.gif

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?

推荐答案

使用 setAttribute 方法:

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" ...>

在JS中使用数据集 property:

And to do it in JS use the dataset property:

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

这篇关于使用JavaScript设置数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆