我有一个选择元素,用户可以从中选择一个值并将其复制到文本区域元素。除了选择元素的值被复制两次之外,一切都按预期工作。
$('#cp_objs_for_goal_button').mouseup(function(){
if ($("#cp_objs_for_goal_select").attr("selectedIndex") != 0)
{
console.log('selected index: '+$("#cp_objs_for_goal_select").attr("selectedIndex"));
curr_txt = $('#pop_goal_text').val();
console.log('curr_txt: '+curr_txt);
added_txt = $('#cp_objs_for_goal_select option:selected').text();
console.log('added_txt: '+added_txt);
if (curr_txt)
{
new_pop_text = curr_txt + ' ' + added_txt;
}
else
{
new_pop_text = added_txt;
}
console.log('new_pop_text: '+new_pop_text);
$('#pop_goal_text').val(new_pop_text);
// TODO - This throws error:
// $('#cp_objs_for_goal_select option').get(0).attr('selected', 'selected');
}
})
当我点击cp_objs_for_goal_button按钮时,从控制台日志中得到了这个信息:
selected index: 1
curr_txt:
added_txt: Restore geomorphic integrity
new_pop_text: Restore geomorphic integrity
selected index: 1
curr_txt: Restore geomorphic integrity
added_txt: Restore geomorphic integrity
new_pop_text: Restore geomorphic integrity Restore geomorphic integrity
以下是HTML代码:
<select id="cp_objs_for_goal_select" style="width:100%">
<option>Select the Objective you would like to copy to this project:</option>
<option>Restore geomorphic integrity</option>
</select>
<div id="cp_objs_for_goal_button" class="awesome" style="border:0;">Copy</div>
#cp_objs_for_goal_button
元素周围的 HTML 吗?如果一个事件处理程序被分配给父级和子级的事件,这种情况经常会发生。例如,看看这个 fiddle(单击任何位置,得到 1 个警报;单击链接,得到 2):http://jsfiddle.net/QLVhr/ - James Allardice