[英]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: 使用创建新HTML元素的最新方法,我执行了以下操作:
$(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. 但是,正如您所看到的,我无法在创建的
<select>
文本属性中插入“真实的” <option>
。 All i get in return is [object Object]
. 我得到的只是
[object Object]
。
I even tried returning .get(0)
, but it didn't work either. 我什至尝试返回
.get(0)
,但也没有用。
I'm not very experienced with JavaScript yet, so i'm just wondering if this is possible. 我不是非常有经验的JavaScript,所以我只是想知道如果这是可能的。 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. 您处在正确的轨道上,但是如果要插入嵌套的html,则需要使用
html
而不是text
。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.