문제

선택 상자의 변경에 따라 다른 기능이 발생하는 가장 좋은 방법을 찾으려고 노력하고 있습니다.

이것은 내 일부 HTML입니다

<select name="event-recurring">
<option selected="true">None</option>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
</select>

내 jQuery는 다음과 같습니다.

$('select[name=event-recurring] option:selected').change (function (){
//Will Do Something
});

다른 값에서 다른 일을하는 것을 어떻게 말합니까?

해결책:

$('#event-recurring').change(function (){
    var $select = $(this);

    switch($select.val()) {
        case "daily":
           $('#recurring-options').remove();
           $("<div id='recurring-options' class='row'><label>Choose:</label>Choose a Date</div>").insertAfter('#recurring');
            break;
        case "weekly" :
        $('#recurring-options').remove();
              $("<div id='recurring-options' class='row'><label>Choose:</label>Weekly</div>").insertAfter('#recurring');
            break;
        case "monthly":
        $('#recurring-options').remove();
           $("<div id='recurring-options' class='row'><label>Choose:</label>Monthly</div>").insertAfter('#recurring');
            break;
        default:
            $('#recurring-options').remove();
            break;
    }    
});
도움이 되었습니까?

해결책

$('select[name=event-recurring]').change (function (){
    var $select = $(this);

    switch($select.val()) {
        case "daily":
            // do something
            break;
        case "weekly" :
            // do something else
            break;
        default:
            // default case
            break;
    }    
});

나는주는 것이 좋습니다 <select> ID도 이름보다 빠르기 때문에 선택하는 데 사용합니다.

다른 팁

이것이 변경 기능 내부에서 작동 할 것이라고 확신합니다.

$('select[name=event-recurring]').change (function (){
    switch ($('option:selected', this).val()) {
      case "daily":
        // do something
        break;
      case "weekly":
        // do something
        break;
      case "monthly":
        // do something
        break;
    }
});

당신은 선택된 값에 따라 다른 것을 의미합니까?

그렇다면 이벤트의 소스 (이 경우 선택)를 참조하기 위해 함수의 '이'객체를 사용할 수 있다고 생각하며 '.val ()'또는 '.text ()'to를 사용하여 값을 확인할 수 있습니다. 그 가치가 무엇인지 확인하고 그에 따라 처리하십시오.

도움이 되었기를 바랍니다.

선택한 값의 하위 쿼리를 사용하고 귀하의 조치의 판별 자로 값 속성을 얻으십시오.

$('select[name=event-recurring]').change( function() {
    var value = $(this).find(':selected').attr('value');
    if (!value) { // none
        do something
    }
    else if (value == 'daily') {
        do something else
    }
    ...
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top