简体   繁体   English

通过ID动态选择

[英]Dynamically Selecting by ID

I have the ID of a selected textarea stored in a variable. 我将所选文本区域的ID存储在变量中。 Is it possible to use that variable to select the element by ID later on in the code? 稍后可以在代码中使用该变量通过ID选择元素吗? For example: 例如:

var currentTextarea = null;

function foo() {
    currentTextarea = 'pageid'; // This will be set dynamically via an event. Example only.
}

function bar() {
    $('#' + currentTextarea).val(); // Although this don't seem to work
}

是的,您的代码应该可以工作-确保在bar()之前调用foo(),否则为空值...

Yes, you can do that; 是的,你可以这么做; I've done that before with no problems. 我已经做到了,没有任何问题。 Make sure currentTextarea is defined before it runs... or make sure nothing else is changing the value (since it's a global variable). 确保currentTextarea在运行之前已定义...或确保没有其他更改值(因为它是全局变量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM