Frage

I have the following structure:

<a title="title 1"> T1 </a>
<a title="title 2"> T2 </a>
...
<a title="title n"> Tn </a>

What I need to do is set the data-filter attribute in each a to the same value as the title, to get this:

<a title="title 1" data-filter="title 1"> T1 </a>
<a title="title 2" data-filter="title 2"> T2 </a>
....
<a title="title n" data-filter="title n"> Tn </a>

So I was trying something like this:

$("a").attr("data-filter", $(this).attr("title"));

My problem is with the $(this) part. I'm trying to reference the current element to use the title. How can I do this? Thank you.

War es hilfreich?

Lösung 2

You're close. $(this) only works when you're in a function. In your case, you want to use $(this) in a function that iterates through all the elements your selector finds, using each:

$("a").each(function() { $(this).attr("data-filter", $(this).attr("title")) });

Here's a basic fiddle.

Andere Tipps

Try using the function arg version of the .attr function,

http://api.jquery.com/attr/#attr-attributeName-functionindex--attr

$("a").attr("data-filter", function () {
    return this.title;
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top