我有以下表格:
$(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语句中的条件。有什么想法吗?
发布于 2015-07-31 07:29:34
简单的解决方案是直接将select标记的值设置为h1中文本的值。
JS代码:
$(function () {
   var selectedText = $('h1').text();
   $('select').val(selectedText);
});Live演示@ JSFiddle:http://jsfiddle.net/dreamweiver/k151ye9h/
发布于 2015-07-31 07:22:25
使用.text()获取<h1>中的文本,并将其与Sandeep进行比较。使用.val()设置<select>的值
if ($("h1").text() == "Sandeep") {
  $("select").val("Sandeep");
}<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>
发布于 2015-07-31 07:25:33
见内联注释
$(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>
https://stackoverflow.com/questions/31740258
复制相似问题