knockout.js Knockoutjs -单击按钮时打开选择下拉列表

nkoocmlb  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(182)

有没有办法在单击其他按钮时打开下拉菜单?

9udxz4iz

9udxz4iz1#

给你!!

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!及其解决方案
更新了针对Knockout的How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?解决方案

相关问题