将属性值添加到HTML标记,其中value等于HTML标记的内容

I've found many similar questions but none quite did the trick for me. Here's my situation: I've got a span, the content of this span is a number dynamically inserted by Jquery. This same span has an attribute, I want the value of this attribute to be equal to the number.

I have tried to put the number in a variable and then add it trough .attr with Jquery but no luck there. Here's the code:

<script>

var value= $('#min').html();
$('#min').attr('data-category', value);

</script> 


<span class="filter" data-category="" id="min"></span>

Any pointers will be greatly appreciated! Thanks :)

You are rendering your script before you render the HTML tag.

You have to either wrap your javascript around the jQuery $(document).ready() to trigger the code once the DOM is ready, or put it after you render the HTML.

<script>

$(document).ready(function() {
    var value= $('#min').html();
    $('#min').attr('data-category', value);
});

</script> 


<span class="filter" data-category="" id="min"></span>

working example

added jquery watch plugin, to catch content changes, maybe exists better solution but this works when you dynamically change your content with jquery

don't forget clear your old content

$('#min').html('');

before inserting new

$('#min').html('new content');

to ensure that watch() function will fire

Thanks a ton for all your help! I've finally figured this out. Ok, so here is how I solved it. This might be a bit more specific then my original question but maybe it can help someone else:

First I use the change event of the Jquery UI slider to detect any changes made on the slider handles:

$( "YOURSLIDER-DIV-SPAN-WHATEVER-ID-CLASS" ).slider({
change: function( event, ui ) {}
});

Then with the value method I put the value of the slider handle in a variable. (since I use a range slider I've got 2 of these, on for the top handle and one for the bottom)

var value = $( "YOURSLIDER-DIV-SPAN-WHATEVER-ID-CLASS" ).slider( "values", 0 );
var value = $( "YOURSLIDER-DIV-SPAN-WHATEVER-ID-CLASS" ).slider( "values", 1 );

Then I use .attr to add the variable to both the bottom and the top slider handles:

$('#min').attr('data-category', bottom_value);
$('#max').attr('data-category', top_value);