jQuery:比较if语句中的字符串是否按预期工作

时间:2018-05-07 14:02:14

标签: javascript jquery

我的代码由于某种原因无效。我已经将问题缩小到变量本身,但我不确定为什么变量不起作用......

var style = $('.user-profiles .custom-field-profileboxstyle td:last-of-type').text();

if (style === 'Sandwich') {
  $('.user-profiles').append("I am a sandwich.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="user-profiles">
  <table>
    <tr class="custom-field-profileboxstyle">
      <td>Profile Box Style:</td>
      <td>Sandwich</td>
    </tr>
  </table>
</div>

当我像这样设置变量时似乎有效:

var style = 'Sandwich';

但是,我需要使用jQuery文本选择器。

3 个答案:

答案 0 :(得分:0)

您的上述代码有效,但styleif比较不起作用的主要原因可能是td中的尾随和前导空格,因此您可以使用trim() style以便删除空格并将其与没有空格的字符串进行比较,如下所示。在字符串比较中使用trim()始终是安全的方法,以便您按预期获得所需的输出。

var style = $('.user-profiles .custom-field-profileboxstyle td:last-of-type').text();

if (style.trim() === 'Sandwich') {
  $('.user-profiles').append("I am a sandwich.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="user-profiles">
    <table>
        <tr class="custom-field-profileboxstyle">
            <td>Profile Box Style:</td>
            <td> Sandwich </td>
        </tr>
    </table>
</div>

答案 1 :(得分:0)

它应该工作。您可能正在尝试在未加载元素时执行脚本。在文档准备好后尝试执行它。 https://learn.jquery.com/using-jquery-core/document-ready/

var style = $('.user-profiles .custom-field-profileboxstyle td:last-of-type').text();
console.log(style);
if (style === 'Sandwich') {
    $('.user-profiles').append("I am a sandwich.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="user-profiles">
    <table>
        <tr class="custom-field-profileboxstyle">
            <td>Profile Box Style:</td>
            <td>Sandwich</td>
        </tr>
    </table>
</div>

答案 2 :(得分:0)

你必须附加一个TD ??因为它可以工作,但是你没有附加一个td,但是你要从表中追加,试试这个......

var style = $('.user-profiles .custom-field-profileboxstyle td:last-of-type').text();
if (style === 'Sandwich') {
    string = 'I am a sandwich.';
    $('.custom-field-profileboxstyle').append("<td>"+string+"</td>");
}