mousedown event on options in select with jquery .on

Deadly 提交于 2021-01-28 11:47:52

问题


I was reading the documentation of the .on event handler of jQuery and I started playing around with it.

I have a simple <select> element with the multiple attribute set to true. However, I want the user to be able to select multiple items without having to press the ctrl or shift key(s)

According to the .on documentation, if you specify a selector it will automatically add those event handlers to any new items added inside that container that match the selector specified.

So in my case, I could for example decide to replace the <option> elements available in the listbox, but I still want to have the same functionality for those options without having to rebind those events etc.

One might think that the following snippet should do the trick (atleast, I did):

$('#dropdownlist').on('mousedown', 'option', function(e){
    e.preventDefault();
    $(this).prop('selected', $(this).prop('selected') ? false : true);
    return false;
});

So when a users clicks on an option in that listbox, the default action will be cancelled and depending wether the item is already selected or not, it will invert that selection.

I have created a small fiddle demonstrating this behaviour: fiddle

In that fiddle, the first dropdownlist is behaving as expected, but the functionality is lost when replacing the items. This only works in FF & Chrome.

The second dropdownlist is how I thought it should've been (event handling wise), but that doesn't seem to work besides in Chrome -.- The functionality is kept when replacing items, because the console will still log '2' when clicking on an item after replacing them.

Can someone explain me why this is happening? Am I doing something wrong? Please point me in the right direction!

Thanks!

~ Dirk


回答1:


IE doesn't respect the mousedown event on the option tag itself. You've got to use the OnChange event of the select tag, which is not what you (nor I) want. I was trying to do the exact same thing as you and was stopped at every attempt. I finally gave up and made it a list of checkboxes because I can get the same behavior out of mine that you are trying to do here.

You can see this question for some options, but I never did get it to work the way you are describing.



来源:https://stackoverflow.com/questions/13260958/mousedown-event-on-options-in-select-with-jquery-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!