jQuery获取data-name作为值

jQuery get data-name as value

本文关键字:data-name 获取 jQuery      更新时间:2023-09-26

我之前用的是

     jQuery( "select#colour option:selected" ).each(function() {
        value += "colour-" + jQuery( this ).val();
    });

这是从下拉菜单中选择的值,并用它构造另一个值。

我现在试图修改这个值(data-name)从下面的html…

<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
谁有类似的例子可以指给我看?

使用.data('name')获取data-name属性值

$(document).ready(function() {
  $('.select-option').each(function() {
    var name = $(this).data('name');
    console.log(name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">

var value;
$('.select-option').each(function(){
  value+=$(this).attr('data-name'); //or $(this).data('name');
});

使用.data()

jQuery( ".select-option" ).each(function() {
        value += "colour-" + jQuery( this ).data("name");
 })