简体   繁体   中英

How can i use a function callback for setting a newly created element attribute?

Fueled by this question, I've been trying to do something that i've never tried before.

Using the latest method of creating new HTML elements, i did the following:

 $(function() { var $element = $('<select>', { class: 'form-control', name: 'dropdownmenu', text: function() { var $test = $('<option>', { value: '1', text: '1' }); return $test; } }); $('p').after($element); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> 

But, as you can see, i couldn't get to insert a "real" <option> to the created <select> text attribute. All i get in return is [object Object] .

I even tried returning .get(0) , but it didn't work either.

I'm not very experienced with JavaScript yet, so i'm just wondering if this is possible. If it is, what can i do to achieve the desired behaviour?

You're on the right track, but you need to use html not text if you want to insert nested html. See the below snippet:

 $(function() { var $element = $('<select>', { class: 'form-control', name: 'dropdownmenu', html: function() { var $teste = $('<option>', { value: '1', text: '1' }); return $teste; } }); $('p').after($element); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> 

Edit - Followup question (multiple options)

You can map over the desired options with minimal change to your code - see the below snippet:

 var options = [1, 2, 3, 4, 5]; $(function() { var $element = $('<select>', { class: 'form-control', name: 'dropdownmenu', html: options.map(function(option) { return $('<option>', { value: option, text: option }) }) }); $('p').after($element); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> 

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