使用 JavaScript 设置自定义属性

编程入门 行业动态 更新时间:2024-10-21 03:33:30
本文介绍了使用 JavaScript 设置自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 The DynaTree (code.google/p/dynatree),但我遇到了一些问题,希望有人能提供帮助..

我在页面上显示树,如下所示:

<ul><li class="文件夹">输出<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

但是,我试图更改项目上的图标,无论它是否被选中或不只使用 JavaScript.

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

我尝试使用以下方法,但似乎不起作用:

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

有人知道我做错了什么吗?

解决方案

使用setAttribute方法:

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

但您确实应该使用数据后跟破折号及其属性,例如:

  • 并在 JS 中使用 dataset 属性:

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

    I am using The DynaTree (code.google/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?

    解决方案

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

  • 更多推荐

    使用 JavaScript 设置自定义属性

    本文发布于:2023-10-27 03:11:51,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1532141.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:自定义   属性   JavaScript

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!