jQuery:包含Selector if else语句

时间:2013-03-20 17:30:02

标签: jquery selector contains if-statement

我有一个结果页面,向用户显示他们在网络表单上的评分。我试图根据他们的答案显示不同的消息。

我已设置基本警报以显示用户选择的内容。

var q1 = $('#webform-component-fieldset-1--question-1').text();
alert(q1);

if ($('#webform-component-fieldset-1--question-1:contains("A. Yes")')) {
    $('.results-wrapper').hide();
    $('.results').append('<div class="popup">User Selected A. Yes, for the first answer.</div>');
}
else if ($('#webform-component-fieldset-1--question-1:contains("B. No")')) {
    $('.results-wrapper').hide();
    $('.results').append('<div class="popup">User Selected B. No, for the first answer.</div>');
}
else if ($('#webform-component-fieldset-1--question-1:contains("C. I do not know")')) {
   $('.results-wrapper').hide();
   $('.results').append('<div class="popup">User Selected C. I do not know, for the first answer.</div>');  
}
else {
   alert('something went wrong');
}

http://jsfiddle.net/Hr6Lj/10/

2 个答案:

答案 0 :(得分:1)

我就是这样做的(使用jQuery的data()函数)(demo

<div class="results">
    <div class="results-wrapper">
        <div class="form-item webform-component webform-component-display" id="webform-component-fieldset-1--question-1"
        data-answer="C">C. I do not know</div>
    </div>
</div>

<script>
  var updateAnswer = function (question) {
    var answer = question.data('answer');
    if (answer === 'A') {
      $('.results-wrapper').hide();
      $('.results').append('<div class="popup">User Selected A. Yes, for the first answer.</div>');
    } else if (answer === 'B') {
      $('.results-wrapper').hide();
      $('.results').append('<div class="popup">User Selected B. No, for the first answer.</div>');
    } else if (answer === 'C') {
      $('.results-wrapper').hide();
      $('.results').append('<div class="popup">User Selected C. I do not know, for the first answer.</div>');
    } else {
      alert('something went wrong');
    }
  }
  updateAnswer($('#webform-component-fieldset-1--question-1'));
</script>

答案 1 :(得分:0)

以下将永远为真,因为对象始终为真。

if ($('#webform-component-fieldset-1--question-1:contains("A. Yes")'))

您想知道是否选择了任何元素。

if ($('#webform-component-fieldset-1--question-1:contains("A. Yes")').length)