简体   繁体   中英

How to set a JavaScript variable in attribute of a HTML tag

I know questions with similar titles have been asked before and I seen the answers.

I have a ul element in HTMl:

<ul class="collection with-header"></ul>

In this element li elements are added dynamically through JavaScript:

$('.collection').append('<li class="collection-item">'+'Hello'+'</li>');

Now,for each li element,I want to add a number to it's class attribute to identify every li element uniquely so that I can assign different id attributes to them.For that I wrote:

var j = 1;
$('.collection').append('<li class="collection-item"'+j+'>'+ 'Hello'+'</li>');
$('.collection-item'+j).attr("id",list[i].username);
j++;

When I try to fetch id of li elements by hover event:

$('.collection-item').hover(
        function(){
        var idd = $(this).attr('id');
        console.log(idd);
        }
 );

Undefined is printed in the console.

What is wrong in this implementation?

EDIT: The value of list[i].username is working fine,it's value is coming from another file and it's not causing any trouble.

Use this instead

var j = 1;
$('.collection').append('<li class="collection-item'+j+'">'+ 'Hello'+'</li>');
$('.collection-item'+j).attr("id",list[i].username);
j++;

There is a syntax error in your code, please use the above code.

For hover to work, do this

$('.collection-item'+j).hover(
        function(){
        var idd = $(this).attr('id');
        console.log(idd);
        }
 );

As far as I can see, your placement of i within that string results in i being outside the html className attribute, infact not inside any html attribute at all. Your code:

$('.collection').append('<li class="collection-item"'+j+'>'+ 'Hello'+'</li>');

would result in this final markup:

<li class = "collection-item"0>Hello</li>
<li class = "collection-item"1>Hello</li>

The zero has no HTML signficance and is out of place.

@sphinx's comment is the correct answer, but it is "not being fired" because his code results in each list item having a unique class name with its number at the end like so:

<li class = ".collection-item0">Hello</li>
<li class = ".collection-item1">Hello</li>

when you add the on hover action, you select these elements by the class ".collection-item", not a unique class.

Your solution would look like this:

$('.collection').append('<li class="collection-item '+j+'">'+ 'Hello'+'</li>');
$('.collection-item.'+j).attr("id",list[i].username);

and with this, in your final markup, each list item will have two classes - a shared "collection-item" class, and a numerical value like so:

<li class="collection-item 0"></li>
<li class="collection-item 1"></li>

now you can select each list item (in this example list item 4) by two classes with the selector $(".collection-item.4") as well as apply an action to all collection items with the selector $(".collection-item") .

I find this code somewhat ugly looking and I'm not sure if I would be happy with it myself in terms of structure if it were mine, but here is a jsfiddle as a proof of concept : https://jsfiddle.net/0wqeouxo/ (click on each list item and it will alert its id)

I think you could get more mileage out of jquery's functionality in that loop rather than defining classes inline.

It a dynamically append element .so you could use on() .and change the selector like this . [class^="collection-item"] It will match same class name element contain with some other name in the class

$(document).on('hover' ,'li[class^="collection-item"]',function(){
        var idd = $(this).attr('id');
        console.log(idd);
        });

As jQuery operates asynchronously, when you try to set the id, the element is might not be in the dom yet. You could set the id before appending the element, for example:

$('<li class="collection-item '+j+'">'+ 'Hello'+'</li>')
  .attr("id",list[i].username)
  .appendTo('.collection');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM