【问题标题】:How to use js variable in jQuery selector [duplicate]如何在 jQuery 选择器中使用 js 变量
【发布时间】:2022-01-27 01:49:35
【问题描述】:

如何在 jQuery 选择器中使用 JavaScript 变量?

(function($){

var words = $('#readpcd').text().match(/(\w+)/g);
if (words.length) {
    var lastword = words[words.length - 1];
}
console.log(lastword);
 
$('select option[value=" + this.lastword +"]').attr("selected","selected");


}(jQuery || window.jQuery));

我试过了

$('select option[value="${lastword}"]').attr("selected","selected");

【问题讨论】:

  • 模板文字需要使用反引号 (`) 而不是单引号

标签: javascript jquery


【解决方案1】:

两种方法:

  1. 字符串连接

    $('select option[value="'+lastword+'"]')
    
  2. 变量注入

    $(`select option[value="${lastword}"]`)
    

(你需要使用`而不是')

【讨论】:

    【解决方案2】:

    使用模板文字(使用反引号``

     $(`select option[value="${lastword}"]`).attr("selected","selected");
    

    【讨论】:

      【解决方案3】:

      你可以使用

      $('select option[value=' + lastword + ']').attr("selected","selected");
      

      【讨论】:

        【解决方案4】:

        改变这一行

        $('select option[value=" + this.lastword +"]').attr("selected","selected");
        

        到这里

        $('select option[value="' + lastword + '"]').attr("selected","selected");
        

        lastword 是一个局部变量。您不能将其用作 this.lastword。

        如果你想内联使用它,请使用反引号

        $(`select option[value="${lastword}"]`).attr("selected","selected");
        

        【讨论】:

        • 谢谢,但是如果我使用 $('select option[value="text"]').attr("selected","selected");它工作
        • 我更新了我的答案,如果你想用反引号@MattSmith
        • 我相信第二行代码仍然不正确,您缺少引号来破坏字符串。
        • 谢谢@Danbardo,我更正了
        猜你喜欢
        • 2012-06-13
        • 2011-08-19
        • 2010-12-23
        • 1970-01-01
        • 1970-01-01
        • 2021-01-29
        • 2017-07-12
        • 1970-01-01
        • 2016-04-26
        相关资源
        最近更新 更多