Find specific attribute and get its value

时间:2017-11-13 06:38:46

标签: jquery find attr

I have this:

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

and need to find the "voice" attribute and fetch its value "next" I tried this by looking all the question but it shows undefined.

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

5 个答案:

答案 0 :(得分:0)

You can use [voice] selector to select your element and attr() method to get attribute value. After that use split() method to get your value. like following.

 $("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>

答案 1 :(得分:0)

try like this

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

play here if you want https://jsfiddle.net/up9ub1uh/

and it's better to use data-voice instead just voice attribute.

答案 2 :(得分:0)

Try this.

$(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>

答案 3 :(得分:0)

try with this code

$(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>

答案 4 :(得分:0)

您不需要使用.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>