根据h1文本设置选择值

时间:2015-07-31 07:17:28

标签: javascript jquery if-statement

我有以下表格:

$(function() {
    if () {}
    else {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Sandeep</h1>
<form>
    <select>
        <option>Non Selected</option>
        <option selected>Michael</option>
        <option>Sandeep</option>
    </select>   
</form>

我想在javascript中找到一种说法:如果h1的文字是Sandeep,则所选的选项将为sandeep

我不知道如何在if语句中定义条件。有什么想法吗?

4 个答案:

答案 0 :(得分:3)

使用.text()获取<h1>中的文字,并将其与Sandeep进行比较。使用.val()设置<select>

的值

&#13;
&#13;
if ($("h1").text() == "Sandeep") {
  $("select").val("Sandeep");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Sandeep</h1>
<form>
  <select>
    <option>Non Selected</option>
    <option selected>Michael</option>
    <option>Sandeep</option>
  </select>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

简单的解决方案是直接将select标记的值设置为h1内的文本的值。

JS CODE:

$(function () {
   var selectedText = $('h1').text();
   $('select').val(selectedText);
});

现场演示@ JSFiddle:http://jsfiddle.net/dreamweiver/k151ye9h/

答案 2 :(得分:0)

参见内联评论

$(function() {
    var text=$('.name').text(); //get the header value by referring its class
    $('select').find("option[text=" + text + "]").attr("selected", true);
    //^^Find that particular option whose text is same as in header
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1 class="name">Sandeep</h1>
<form>
    <select>
      <option>Non Selected</option>
      <option text="Micheal" selected>Michael</option> 
      <option text="Sandeep">Sandeep</option>
      <!--Add text property to each option-->
    </select>   
</form>

答案 3 :(得分:0)

只需使用Jquery选择器根据“h1”选择值。

$(document).ready(function() {
  if ($("h1").text() == "Sandeep") {
    $("select").val("Sandeep");

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Sandeep</h1>
<form>
  <select>
    <option>Non Selected</option>
    <option selected>Michael</option>
    <option>Sandeep</option>
  </select>
</form>