如何仅定位与on(change)事件处理程序关联的类?

时间:2015-12-12 21:58:28

标签: javascript jquery javascript-events event-handling

我已经创建了一个三问题调查,根据所选的选项,用户会收到更多详细信息或错误消息。我需要消息只切换事件发生的当前表单。如何仅定位与当前事件关联的类?

(function() {
 $('.styled-select').on('change', function() {
    var id = $('option:selected').parent().attr('id');
    console.log(id);

    var $wrongAnswer = $(this).parent().filter('.wrong-answer');
    var $story       = $(this).parent().filter('.story');


    if ( $.inArray( $(this).val(), ['artisan', 'hipster', 'meditation', 'cardigan'] )) {
        $wrongAnswer.removeClass('expand');
        $story.addClass('expand');

    } else {
        $wrongAnswer.addClass('expand');
        $story.removeClass('expand');
    }

 });
})();

HTML

<section id="q-three" class="survey">
<form action="">
    <select name="" id="select-three" class="styled-select" >
        <option default>Select one</option>
        <option value="artisan">artisan</option>
        <option value="humblebrag">humblebrag</option>
        <option value="brooklyn">brooklyn</option>
        <option value="kickstarter">kickstarter</option>
    </select>
    <h2>Put a bird on it kogi master cleanse try-hard salvia.</h2>

    <div class="story">
        <h3>Pickled letterpress 3 wolf moon crucifix. Migas artisan thundercats, four loko keytar chicharrones shabby chic drinking vinegar knausgaard portland street art occupy small batch. </h3>
    </div>
    <div class="wrong-answer">
            <h3>Try again!</h3>
    </div>
</form>

Live demo

1 个答案:

答案 0 :(得分:0)

使用div换取每个问题,因此$wrongAnswer$story仅在div中使用当前问题进行搜索,而不是整个表单。

<section id="q-three" class="survey">
<form action="">
  <div>
    <select name="" id="select-three" class="styled-select" >
        <option default>Select one</option>
        <option value="artisan">artisan</option>
        <option value="humblebrag">humblebrag</option>
        <option value="brooklyn">brooklyn</option>
        <option value="kickstarter">kickstarter</option>
    </select>
    <h2>Put a bird on it kogi master cleanse try-hard salvia.</h2>

    <div class="story">
        <h3>Pickled letterpress 3 wolf moon crucifix. Migas artisan thundercats, four loko keytar chicharrones shabby chic drinking vinegar knausgaard portland street art occupy small batch. </h3>
    </div>
    <div class="wrong-answer">
            <h3>Try again!</h3>
    </div>
  </div>
</form>

此外,在脚本中,使用.find()代替.filter()

var $wrongAnswer = $(this).parent().find('.wrong-answer');
var $story       = $(this).parent().find('.story');