addEventListener,“更改”和选项选择 [英] addEventListener, "change" and option selection

查看:123
本文介绍了addEventListener,“更改”和选项选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图让动态选择列表自己填充,从一个选择开始:

So I'm trying to have dynamic select list populate itself, from a single selection to start:

<select id="activitySelector">
      <option value="addNew">Add New Item</option>
</select>

然后我们有JavaScript代码:

and then JavaScript code we have:

addEventListener("select", addActivityItem, false); 

问题是当你有一个项目时不会触发各种事件:不是改变,因为,选择该项目时,文字没有什么不同;不是选择(因为我在这里),原因大致相似,因为我并没有真正选择任何东西b / c只有一个项目。应该在这里解雇的事件是什么?在我的选项列表中列出一个空白项来触发事件似乎很愚蠢,所以我希望有另一个解决方案。或者这是最好的解决方案?

The problem is that various events don't fire when you have one item: not "change" because, the text is no different when you select that item; not "select" (as I have here), for a roughly similar reason, because I'm not really selecting anything b/c there's only one item. What is the event that should be fired here? It seems silly to list a blank item in my option list to fire the event, so I hope there is another solution. Or is that the best solution?

推荐答案

您需要一个点击事件来处理您所描述的行为。

You need a click event to handle the kind of behavior you've describe.

首先,检查是否已存在多个选项。

First, check to see if more than one option already exists.

如果没有,请拨打 addActivityItem function。

If not, call your addActivityItem function.

以下代码段演示了如何实现这一目标:

The following snippet demonstrates how you may achieve that:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)
    {
        addActivityItem();
    }
});

activities.addEventListener("change", function() {
    if(activities.value == "addNew")
    {
        addActivityItem();
    }
});

function addActivityItem() {
    // ... Code to add item here
}

现场演示此处为JSfiddle

这篇关于addEventListener,“更改”和选项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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