Knockoutjs - 点击按钮打开选择下拉菜单

时间:2016-04-26 01:35:08

标签: javascript jquery knockout.js javascript-events

有没有办法在点击其他按钮时打开下拉列表?

1 个答案:

答案 0 :(得分:2)

在这里你去!!

<强> JS

function VM() {
  var message = ko.observable("hello!!");

  function onButtonClick() {
   var dropdown = document.getElementById('dropdown');    
   showDropDown(dropdown);
}  

function showDropDown(element){
  var event;
  event = document.createEvent('MouseEvents');
  event.initMouseEvent('mousedown', true, true, window);
  element.dispatchEvent(event);
}

return {
  message: message,
  onButtonClick:onButtonClick
   }
 }

ko.applyBindings(new VM());

<强> HTML

   <button data-bind="click: onButtonClick">
     Button
   </button>
   <select id="dropdown" >
     <option>1</option>
     <option>2</option>
     <option>3</option>
     <option>4</option>
   </select>

这是JSFiddle!解决方案

更新了How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?针对Knockout的解决方案