用于变量的jQuery语法

时间:2022-12-07 00:12:38

jQuery not working with variable. the issue is with this line:

jQuery没有使用变量。问题出在这一行:

$('img[alt = id]').trigger("click");

if I change it to

如果我改成它

$('img[alt = "6"]').trigger("click");

Everything works as expected. I just can't workout how to use a variable instead of a value within the quotes. I have tried putting id in single / double quotes with no luck. I'm sure it will be something obvious. Can anyone help.

一切都按预期工作。我只是无法锻炼如何使用变量而不是引号内的值。我试过把id放在单/双引号中而没有运气。我相信这将是显而易见的事情。谁能帮忙。

This is the full code.

这是完整的代码。

$(window).load(function () {
        // run code
       // $('img[alt ="6"]').trigger("click");
        var id = localStorage.getItem("CustomerID");
        $('img[alt = id]').trigger("click");
      //  window.alert(id);
    });

2 个解决方案

#1


3  

You can combine a string and use that instead:

您可以组合一个字符串并使用它:

$('img[alt = "' + 6 + '"]').trigger("click");

Here it is as a variable:

这是一个变量:

var id = 6;
$('img[alt = "' + id + '"]').trigger("click");

It's called string concatenation.

它被称为字符串连接。

#2


1  

Watch this

看这个

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Example:

例:

$(`img[alt = "${id}"]`).trigger("click");

#1


3  

You can combine a string and use that instead:

您可以组合一个字符串并使用它:

$('img[alt = "' + 6 + '"]').trigger("click");

Here it is as a variable:

这是一个变量:

var id = 6;
$('img[alt = "' + id + '"]').trigger("click");

It's called string concatenation.

它被称为字符串连接。

#2


1  

Watch this

看这个

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Example:

例:

$(`img[alt = "${id}"]`).trigger("click");