【问题标题】:drop down with onchange events下拉 onchange 事件
【发布时间】:2011-11-19 12:17:58
【问题描述】:

我有一个包含onchange 事件的下拉列表。当用户更改下拉框时,调用 ajax 并显示结果。这一切都很好。

我在模板中有以下列表。

Apple
Pineapple

当用户更改下拉值时。然后结果合并

Orange
Graps

Apple
Pineapple

但是输出应该是这样的。

Orange
Graps

我不知道该怎么做。请帮我。这是我的base。这是我的movie_list 模板。这是我的movie_sort 模板。这是我的view。谢谢:-)

更新:这里是 ajax 代码。

   function sortMovie(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

    }
  }
xmlhttp.open("GET","/moviesort/?q="+str,true);
xmlhttp.send();

}

下拉

           <select name="category" onchange="sortMovie(this.value)">
                <option value="">Choose</option>
                {% for category in categories %}
                <option value="{{ category.id}}">{{category.name}}</option>
                {% endfor %}                    
                </select>

【问题讨论】:

标签: python django django-templates


【解决方案1】:

如果您使用 jQuery 调用 ajax,我建议您在 .change() 函数之后直接使用 .empty()。

我不知道你的样子,虽然它应该是这样的。

$('#id_category').change(function() {
    /* Set your string to nothing */
    var str = "";
    /* once your dropdown is changed, it performs a look and gets the new data */
    $("#id_category option:selected").each(function () {
        /* Before inserting the new data, empty out all the old items */
        $('#id_sub_category').empty();
        str += $(this).val();
        $.get('{% url gear_category %}', { category: str }, function(data){
            $(data).appendTo("#id_sub_category");
        });
    });
});

希望这会有所帮助。

【讨论】:

  • 我使用的是简单的 ajax 函数而不是 jquery。
【解决方案2】:

我同意 AppPel 的观点。

但是,由于您没有使用 jQuery...

您要么必须遍历 select 中的每个选项并随时删除,或者我想如果纯 javascript 支持您可能能够模仿 jQuery 代码,但使用 javascript 语法。

无论哪种方式,您都必须在添加新值之前删除旧值。这就是问题所在。

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多