如何在Jquery中显示选择选项之前对其进行更新? [英] How to update select options before showing them in Jquery?

查看:185
本文介绍了如何在Jquery中显示选择选项之前对其进行更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的示例代码:

<html>
<head>
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $("body").on('click', "#teste",function(){
          $('#teste').append('<option id="pera">pera</option>')
          $('#teste').show();
        });
      });
    </script>
</head> 
<body>
    <select id="teste">
        <option value="banana">banana</option>
        <option value="laranja">laranja</option>
    </select>

</body>

我的问题是,单击事件仅在使用新值("pera")对其进行更新之后才显示选择框.我需要做的是先用新值更新选择,然后再显示它.无论如何,有使用jQuery来做到这一点的吗?预先感谢,伙计们!

My problem here is that the click event show the select box and only after it updates it with the new value ("pera"). What I need to do is first update the select with the new value and only after show it. Is there anyway to do that using jQuery? Thanks in advance, guys!

好吧,让我尝试解释清楚一点:每当您单击选择以显示选项时,它就会自动显示它(很明显!).我的问题是我需要拦截click事件,更新选择,并且仅在显示选择之后.但它显示更新之前的选择(这是默认行为).这是正在发生的事情:

Ok, let me try to explain a little bit clear: Whenever you click in a select to show the options it show it automatically (it's obvious!). My problem is that I need to intercept the click event, update the select and only after it show the select. But it's showing the select (it's the default behaviour) before updating. Here is what happening:

1)使用初始值进行选择:香蕉,香菜

1) Select with initial values: banana, laranja

2)用户单击它.我想要的是:可以选择显示香蕉,香菜和pera.发生的情况:它在列表中显示香蕉,laranja,仅在更新选择后显示(如果我使用fiebug检查html代码,则可以使用pera选项!).如果我再次单击select,pera选项将正常显示,并且如上面的代码所示,它将在select中附加另一个pera选项,该选项仅在下次单击时出现,依此类推.

2) User click it. What I want: Show banana, laranja and pera as options. What happens: It shows banana, laranja in the list, show it and only after update the select (If I inspect the html code with fiebug, the pera option is there!). If I click again inthe select, the pera options appears normally and as the code above says, it appends another pera option in the select that only appears in the next click and so on.

推荐答案

我有点困惑..您是否只想在页面加载时更新选择?如果是这样,您可以这样做:

I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:

CSS:

#teste {
  display: none;
}

JS:

$(function(){
  $('#teste').append('<option id="pera">pera</option>').val("pera").show();
});

这篇关于如何在Jquery中显示选择选项之前对其进行更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆