使用onclick启用禁用的下拉菜单

时间:2018-08-14 20:38:31

标签: javascript jquery

我有一个禁用的下拉菜单,仅在单击后才希望启用。我尝试了几种方法,以下是最新的无效方法:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function() {

$("input:disabled").closest("div").click(function() {

$(this).find("input:disabled").attr("disabled", false).focus();

});

});

<div>
  <select name="test" id='testing' disabled>
<option name="first" value='first'>first</option>
<option name="second" value="second">second</option>
</select>
</div>

2 个答案:

答案 0 :(得分:1)

SCNSphere
$(function() {

	$('div > div').on('click', function(event) {

		$(this).hide().prev('select:disabled').removeAttr('disabled').focus();
		
	});

});

答案 1 :(得分:1)

这将通过使用CSS在选择项之上添加一个图层来检测对它的单击,但这仍然不是最好的选择,因为它仍然需要用户采取更多操作才能打开选项。因此,基本上是双击。

var elem = document.querySelector('span.cover');

function listener () {
  elem.classList.remove('active');
  elem.removeEventListener('mousedown', listener)
  var sel = elem.querySelector('select');
  sel.removeAttribute('disabled');
  sel.focus();
}


elem.addEventListener('mousedown', listener)
span.cover {
    position:relative;
}
span.active.cover:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
<span class="cover active">
  <select name="test" id='testing' disabled>
<option name="first" value='first'>first</option>
<option name="second" value="second">second</option>
</select>
</span>

如果您想使用jQuery

$(document).on('click','span.active', function(){
  $(this).removeClass('active').find('select').removeAttr('disabled');
})
span.cover {
    position:relative;
}
span.active.cover:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="cover active">
  <select name="test" id='testing' disabled>
<option name="first" value='first'>first</option>
<option name="second" value="second">second</option>
</select>
</span>

<span class="cover active">
  <select name="test" id='testing2' disabled>
<option name="first" value='first'>first</option>
<option name="second" value="second">second</option>
</select>
</span>