简体   繁体   中英

How do I let the DOM know about new elements created on the fly?

I am making an AJAX call and I am building some HTML on the backend side. I am returning them as a JSON and then using jQuery I render them, something like:

$(data.message).each(function (index, value) {
    $('#states_table tbody').append('<td>' + value.edit_link + '</td>');
});

value.edit_link contains the following HTML:

<a id="edit_0" 
   title="Edit" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</a>

Then I will end up with something like this:

在此处输入图片说明

And as you can see the link doesn't have the hand cursor. My guess is that the DOM doesn't know about them when the page is rendered for first time so no CSS properties or default properties will be applied which makes me ask:

In order to have the links with the cursor: hand , how do I let the DOM know about this new elements?

Solution 1

Add to your link html href="#" or href="javascript:void(0)" so:

<a href="#"
   id="edit_0" 
   title="Edit" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</a>

For a full comprehension of <a> html tag read this .

If you don't know if is better href="#" or href="javascript:void(0)" (nobody knows) read this discussion .

Solution 2

Don't use an <a> but a <button> following the sentiment :

if <a> button doesn't have a meaningful href, it's a <button>

(for someone a <button> outside a <form> feels wrong. You decide.)

so:

<button id="edit_0" 
   onclick="javascript:return false;" 
   class="edit"
>Edit</button>

Button reference there .

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