gpt4 book ai didi

javascript - 获取元素的 ID 并将其设置为变量

转载 作者:可可西里 更新时间:2023-11-01 13:17:38 24 4
gpt4 key购买 nike

我有一个按钮:

<button class="btn btn-info continue">
<i class="ace-icon fa fa-check bigger-110"></i>
Continue
</button>

点击:

$(".continue").click(function(e) {
currForm = $(this).parents('form');
e.preventDefault();
});

我可以很容易地获得 ID:currForm.attr('id'); , 但我可以将此 id 的值设置为变量吗?

类似于php的可变变量:

$a = 'hello';
$$a = 'world';
echo $hello;

编辑:我不想更改元素的 ID。我想获取此 ID 并将其用作 javascript 变量的名称。例如,我上面提供的元素在 form 中ID='example_id'。 currForm.attr('id')会给我example_id我想设置一个变量 example_id并为其赋值。

var example_id = 'some value';

最佳答案

这里有 3 个选项供您选择。

eval(不推荐)

您可以使用 Javascript 函数 eval实现你想要的。但请注意,不推荐(我强调了两次,希望您能理解!)。

Don't use eval needlessly!

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

它会像这样使用:

eval('var ' + varName + ' = "something";');

Window object notation(比eval更好,仍然不推荐)

此方法包括在全局窗口对象上使用 JavaScript 提供的对象表示法。这污染了全局窗口范围,并且可以被其他 JS 文件覆盖,这是不好的。如果您想了解更多关于该主题的信息,这是一个很好的问题:Storing a variable in the JavaScript 'window' object is a proper way to use that object? .

要使用此技术,您需要执行以下操作:

window[varName] = something;
alert(window[varName]);

使用对象(推荐)

最好的解决方案是创建您自己的变量范围。例如,您可以在全局范围内创建一个变量并为其分配一个对象。然后,您可以使用对象表示法来创建动态变量。它的工作方式与窗口相同:

var globalScope = {};

function awesome(){
var localScope = {};
globalScope[varName] = 'something';
localScope[varName] = 'else';

notSoAwesome();
}

function notSoAwesome(){
alert(globalScope[varName]); // 'something';
alert(localScope[varName]); // undefined
}

关于javascript - 获取元素的 ID 并将其设置为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com