How can I get a HTML data value as a string with jQuery?

后端 未结 7 822
面向向阳花
面向向阳花 2021-01-31 18:02

I have the following in my source HTML:

  • Test
  • I want to get the value of th

    相关标签:
    7条回答
    • 2021-01-31 18:19

      From the jQuery data() documentation, it appears that you have to use .attr() to prevent the automatic type conversion:

      Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

      So, not to duplicate other answers, but rather to reinforce, the way to access the attribute without doing type conversion is:

      var abc = $(this).attr('data-value');
      
      0 讨论(0)
    • 2021-01-31 18:20
      $(this).attr('data-value');
      

      This will return the string value with the leading 0.

      0 讨论(0)
    • 2021-01-31 18:23
      <article id="electric-cars" data-columns="3"data-index-number="12314" data-parent="cars">
      
      </article>
      
      
      const article = document.querySelector('#electric-cars');
       
      article.dataset.columns // "3"
      article.dataset.indexNumber // "12314"
      article.dataset.parent // "cars"
      
      0 讨论(0)
    • 2021-01-31 18:27
      this.dataset.value;
      
      // Or old school
      this.getAttribute('data-value');
      

      const a = document.querySelector("a");
      console.log('Using getAttribute, old school: ', a.getAttribute('data-value'));
      console.log('Using dataset, conforms to data attributes: ', a.dataset.value);
      <ul>
        <li><a href="#" data-value="01">Test</a></li>
      </ul>

      Thanks to @MaksymMelnyk for the heads up on dataset

      0 讨论(0)
    • 2021-01-31 18:28

      have you tried?:

      $(this).attr('data-value');
      

      or

      $(this).attr('data-value').toString();
      
      0 讨论(0)
    • 2021-01-31 18:31

      Try :

      this.data('value');
      

      I think this is best way to get data attribute value.

      0 讨论(0)
    提交回复
    热议问题