查找特定属性并获取其值

Find specific attribute and get its value

我有这个:

<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>

并且需要找到 "voice" 属性并获取其值 "next" 我通过查看所有问题来尝试这个,但它显示未定义。

$(document).ready(function(){
    $("button").click(function() {
    var ab = $(document).find("[voice=' ']")[0];
    console.log(ab);
    });
});

您可以使用 [voice] select 或 select 您的元素和 attr() 方法来获取属性值。之后使用 split() 方法获取您的值。喜欢以下。

 $("button").click(function() {
    var ab = $("[voice]"),
        text = ab.attr('voice').split(',')[0];
    console.log(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>

像这样尝试

$(document).ready(function(){
    $("button").on('click', function() {
    var ab = $(document).find("[voice]").attr('voice');
    console.log(ab);
    });
});

想玩就在这里玩https://jsfiddle.net/up9ub1uh/

最好使用 data-voice 而不是 voice 属性。

试试这个。

$(document).ready(function(){
    $("button").click(function() {
    var ab = $("p").attr('voice');
    console.log(ab);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>

尝试使用此代码

$(document).ready(function() {
  $("button").click(function() {
    var ab = $(".intro").attr('voice');
    var new1 = ab.split(",");
    console.log(new1[0]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click</button>
<p class="intro" voice="next,1">My name is Donald.</p>

您不需要使用 .find,如您在本例中所见:

<p>Once there was a <em title="huge, gigantic">large</em> dinosaur...</p
 <script>
 var title = $( "em" ).attr( "title" );
 console.log(title);
 </script>

你应该只这样做:

<p class="intro" voice="next,1">My name is Donald.</p>
 <script>
 var title = $( "p" ).attr( "voice" );
 console.log(title);
  </script>