Get the custom attribute value of div

The shuttle box of antD is used in the project. When customizing the styles on the left and right sides, it is necessary to distinguish the direction. Using class or id does not feel semantic enough, so I thought of custom attributes. Let's see how to achieve it.

Learn how jq implements:

<div id="test" width="50">测试</div>

int w = $("#test").attr("width");

console.log(w); // 50

Let's take a look at how js is implemented: (single)

<div id="xxx" customAttr="test">测试</div>

const a = document.getElementById("xxx").attributes["customAttr"].value;

alert(a);    // 测试

This is only a single one, because multiple divs are selected in the project, and what you get is an array, so I thought of the new method of getting custom attributes in H5 (there is a compatibility problem, supported by IE11 and above), and  traverse to get all:

Syntax: HTMLElement.dataset.property|| HTMLElement.dataset['property'];

Description: 1). H5's newly added method for obtaining custom attributes, it can only obtain data- at the beginning;

         2). dataset is a collection, which stores all custom attributes starting with data-;

         3). It is recommended that when setting custom attributes in the future, no matter which method is used, the attribute name starts with data-, eg: data-direction; 

         4). If there are multiple-linked words in the custom attribute, we use the camel case naming method when we get it, eg: data-list-name, when we get it, it is HTMLElement.dataset.listName or HTMLElement.dataset['listName' ].

<div className="container">
      {sourceData.map(item => (
            <div
              className="custom-item"
              data-direction='left'
              key={item.key}
            >
            {item.name}
            </div>
        ))
      }
      {targetData.map(item => (
            <div
              className="custom-item"
              data-direction='right'
              key={item.key}
            >
            {item.name}
            </div>
         ))
       }
</div>

 Take a look at the printout:

 As you can see, you can get custom attribute values, so just continue to write logic according to different attribute values!

Reference:  https://www.csdn.net/tags/MtjaEg1sNTE3NDEtYmxvZwO0O0OO0O0O.html

 

Guess you like

Origin blog.csdn.net/BUG_CONQUEROR_LI/article/details/126666684