[英]How do I access an element if the id which I want to access is stored in a variable
I am trying to dynamically create elements and hence dynamically giving them the value. 我试图动态创建元素,从而动态地为其赋予值。 So if I want to access an element using a value which is stored in a variable, how do I do that ? 因此,如果我想使用存储在变量中的值访问元素,该怎么做?
I've tried using $("#'"+g+"'")
but it didn't work 我试过使用$("#'"+g+"'")
但是没有用
var text1 = '<div id="' + g + '"></div>';
var text2 = '<input data-checkbox="' + g + '" type="checkbox" style="display:none;"/><h3 data-header="' + g + '" style="display:inline-block;">Timer' + g + ' </h3><input data-input="' + g + '" type="text" style="display:none;"/>';
var text3 = '<span data-minutes="' + g + '">00</span>:<span data-seconds="' + g + '">00 </span><button data-start="' + g + '" >start</button><button data-stop="' + g + '" style="display:none;">stop</button><button data-clear="' + g + '" style="display:none;">clear</button>';
$('#header').append(text1);
$("#'"+g+"'").append(text2, text3);
This should be all you need: 这应该是您所需要的:
$("#" + g)
The fact it's a string is already implied. 事实上,它是一个字符串。
You're quite close to getting this right; 您已经很接近正确了。 the comments are trying to tell you that you aren't forming the selector correctly. 这些评论试图告诉您您没有正确形成选择器。
The selector for an id must be a string in the form: ID的选择器必须是以下形式的字符串:
'#id'
In your example you have too many '
symbols, so the id from your variable g
will be in the string, but surrounded by variables. 在您的示例中,您有太多的'
符号,因此变量g
的id将在字符串中,但被变量包围。 If g
was test-id
, you'd have the string: 如果g
是test-id
,则将具有以下字符串:
"#'test-id'"
...and jQuery can't match that. ...而jQuery无法与之匹敌。
All you need to do is take out those quotes, here's how that might look: 您需要做的就是去掉那些引号,这看起来可能是这样:
var g = 'any-id'; var text1 = '<div id="' + g + '"></div>'; var text2 = '<span>Some other text</span>'; $('#header').append(text1); $('#' + g).append(text2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="header">Header is here</div>
You just have a small mistake. 您只是有一个小错误。
You need to try like this $("#"+g).append(text2, text3);
您需要这样尝试$("#"+g).append(text2, text3);
var g = "data"; var text1 = '<div id="' + g + '"></div>'; var text2 = '<input data-checkbox="' + g + '" type="checkbox" style="display:none;"/><h3 data-header="' + g + '" style="display:inline-block;">Timer' + g + ' </h3><input data-input="' + g + '" type="text" style="display:none;"/>'; var text3 = '<span data-minutes="' + g + '">00</span>:<span data-seconds="' + g + '">00 </span><button data-start="' + g + '" >start</button><button data-stop="' + g + '" style="display:none;">stop</button><button data-clear="' + g + '" style="display:none;">clear</button>'; $('#header').append(text1); $("#"+g).append(text2, text3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="header"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.