简体   繁体   English

将onclick事件附加到一个元素的下拉列表中

[英]Attach onclick event to a dropdown with one element

I have a dropdown. 我有一个下拉菜单。 Initially it is empty and at some point it is filled with elements dynamically. 最初它是空的,有时它会动态地填充元素。 When the user choose an option the onchange event is triggered. 当用户选择一个选项时,将触发onchange事件。 This works when there are at least two values in the dropdown. 当下拉列表中至少有两个值时,此方法有效。

What I want to accomplish is, when there is only one element in the dropdown and the user clicks it, some event to be triggered. 我要完成的是,当下拉列表中只有一个元素并且用户单击它时,将触发一些事件。 I tried the onclick event but this does not worked on the dropdown. 我尝试了onclick事件,但这在下拉列表中不起作用。

Here is my jsfiddle: 这是我的jsfiddle:

http://jsfiddle.net/MwHNd/551/ http://jsfiddle.net/MwHNd/551/

Some option may be to have defaut value like "Choose an option" in the dropdown and this way the onchange will always trigger. 一些选项可能具有默认值,例如下拉菜单中的“ Choose a option”(选择一个选项),这样onchange总是会触发。 Is there are way to do it without this option? 没有此选项,有没有办法做到这一点?

well its not as simple as that, there are two aways you can go about doing this, both requires if statements.. you can either "dyamically" in js see how many options there are in a selector and tell it to change the element to a button OR do a focus function with jquery if there is only one element in your dropdown $selector.focus(function(){ then whatever you wants etc also you said you would not want to do this with a drop down. use a javascript function to click the event plus the selected index of the option values you want 嗯,它不是那么简单,您可以执行以下两项操作,都需要if语句。.您可以在JS中“动态地”查看选择器中有多少个选项,并告诉它将元素更改为一个按钮,或者如果您的下拉列表中只有一个元素$selector.focus(function(){则无论您想要什么,也说您不希望通过下拉列表执行此操作),都可以使用jquery来实现焦点功能。单击事件以及所需选项值的选定索引的函数

function change(){
    document.getElementById("your-element").selectedIndex =2;
}
function changeit(){
    document.getElementById("your element").selectedIndex =1;
}
function changeitup(){
    document.getElementById("your element").selectedIndex =0;
}

so if you wanted the selected index plus the event you want to do 因此,如果您想要选择的索引加上您要执行的事件

<input type='button' onclick="change();otherfunction()"> would give you the selected index plus the function you wanted originally <input type='button' onclick="change();otherfunction()">将为您提供选定的索引以及您最初想要的功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM