javascript 使用 .append() 添加标题属性以动态选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20227484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding title attribute to select option dynamically with .append()
提问by dah97765
Javascript, Jquery, HTML
Javascript、Jquery、HTML
I am adding select options to a select box dynamically. I take each unique element in an array and add it as an option to the select element. It works great, but I need to add a title attribute at the same time, with the same value as the option text. The end goal of this is to make tooltips for each option.
我正在动态地向选择框添加选择选项。我将数组中的每个唯一元素作为选项添加到 select 元素中。效果很好,但我需要同时添加一个标题属性,其值与选项文本相同。这样做的最终目标是为每个选项制作工具提示。
So instead of <option>value</option>
, it looks like
所以,而不是<option>value</option>
,它看起来像
<option title="value">value</option>
Does that make sense?
那有意义吗?
Current HTML:
当前的 HTML:
<select id="Process_Issue" class="fieldLabel2 IncidentInputField dynamicFields1"></select>
JS:
JS:
$.each(eliminateDuplicates(aryProcess), function (key, value) { $('#Process_Issue').append($("<option/>", { text: cleanNulls(value) })); });
采纳答案by MonkeyZeus
You can just specify the title upon appending:
您可以在附加时指定标题:
HTML
HTML
<select id="my_select"></select>
JS
JS
$('#my_select').append('<option title="value1">value1</option>');
$('#my_select').append('<option title="value2">value2</option>');
$('#my_select').append('<option title="value3">value3</option>');
回答by Shyju
You can set the title
attribute
你可以设置title
属性
$('#Process_Issue').append(
$("<option/>", { text: value }).attr("title",value)
);
Here is a working sample http://jsbin.com/ozudoTod/1/
这是一个工作示例http://jsbin.com/ozudoTod/1/
回答by kkemple
A cleaner way is to create the element before with all values then append like so:
一种更简洁的方法是在所有值之前创建元素,然后像这样附加:
value = cleanNulls( value );
var option = $( '<option/>', {
title: value,
text: value
});
$('#Process_Issue').append( option );
this method is a lot cleaner and easier to read / maintain
这种方法更干净,更容易阅读/维护
回答by Sushanth --
You seem to be using the same selector multiple times for each iteration in the array. Instead cache it and save some lookup time.
您似乎在数组中的每次迭代中多次使用相同的选择器。而是缓存它并节省一些查找时间。
var $select = $('#Process_Issue');
$.each(eliminateDuplicates(aryProcess), function (key, value) {
var val = cleanNulls(value);
$select .append($("<option/>", {
text: val,
title: val
}));
});
If this does not work use .attr
method to hook up the attribute to the element.
如果这不起作用,请使用.attr
方法将属性连接到元素。
var $select = $('#Process_Issue');
$.each(eliminateDuplicates(aryProcess), function (key, value) {
var val = cleanNulls(value);
$('<option/>').attr({
text: val,
title: val
}).appendTo($select);
});