jQuery와 함께 의 변경 이벤트를 잡는 방법은 무엇입니까?
-
05-07-2019 - |
문제
<select id="target">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
</select>
선택한 값에 따라 약간의 처리를하고 싶습니다.
해결책
$('#target').change( function() {
$(this).find(":selected").each(function () {
console.log( $(this).val() );
});
});
다른 팁
$("#target").change( function() {
alert($("#target option:selected").val());
});
사람이 옵션을 변경하지 않고 드롭 다운을 클릭하고 동일한 항목을 선택하는 경우이를 고려해야 할 수도 있습니다.
$("#target option").click( function() {
alert($("#target option:selected").val());
});
$("#target").change( function() {
var selectedOption = $("#target option:selected");
var selectedValue = selectedOption.val(); // gets the selected value
var selectedText = selectedOption.text(); // gets the selected text
});
허용 된 대답은 괜찮지 만 Keypress (화살표 키 또는 알파늄 키)에 의해 변경되지는 않습니다.
이것은 더 나은 apporach입니다 :
$('#target').bind("change keyup",function() {
$(this).find(":selected").each(function () {
// do something amazing here
});
});
선택한 값과 텍스트를 간단히 얻을 수 있습니다.
$("#target").change(function() {
var selectedValue = $(this).val(),
selectedText = $('option:selected', this).text();
// ...
});
화살표 기능을 사용하면 다음과 같습니다.
$('#target').change((e) =>{
console.log(e.currentTarget.value);
console.log(e.currentTarget.textContent);
});
교체 this
~에 의해 event.currentTarget
.
제휴하지 않습니다 StackOverflow