[英]jquery/javascript finding the value within a dynamically created element id
I have a dynamically generated html table whose columns have id assigned dynamically.我有一个动态生成的 html 表,其列的 id 是动态分配的。 for ex:例如:
<td id="1">1</td>
<td id="2">2</td>
....
....
<td id="n">n</td>
in order to get the get value of a specific column I am using document.getElementById("#myvar").innerHTML
or $("td#myvar").html
where myvar is variable that contains search element such as 2 or 3 etc. But I dont get any results.为了获取特定列的获取值,我正在使用document.getElementById("#myvar").innerHTML
或$("td#myvar").html
,其中 myvar 是包含搜索元素(例如 2 或 3 等)的变量. 但我没有得到任何结果。 If I direcly use a number for document.getElementById("#2").innerHTML
, it works.如果我直接为document.getElementById("#2").innerHTML
使用一个数字,它就可以工作。 Please advise what to do to get value where id of element is same as the variable declared??请告知如何获取元素 id 与声明的变量相同的值?
First, the getElementById()
DOM method expects an ID, not a jQuery selector.首先, getElementById()
DOM 方法需要一个 ID,而不是 jQuery 选择器。
Second, neither JavaScript nor jQuery provide variable interpolation in strings, as you seem to be assuming.其次, JavaScript 和 jQuery 都不提供字符串中的变量插值,正如您所假设的那样。 You have to build your own string:你必须建立自己的字符串:
var myvar = 2;
$("td#" + myvar).html()
Last but not least, remember that the ID attribute cannot start with a digit unless you are using HTML 5.最后但同样重要的是,请记住 ID 属性不能以数字开头,除非您使用 HTML 5。
use this -用这个 -
$("#"+myVar).html();
Your code is wrong.你的代码是错误的。 When using document.getElementById, you don't include the # sign.使用 document.getElementById 时,不包含 # 符号。 When using jQuery id selectors, you do use the # sign, but you need to call.html() as a function.当使用 jQuery id 选择器时,您确实使用了 # 符号,但您需要将 call.html() 作为 function。
document.getElementById("myvar").innerHTML
$('#myvar').html();
If myvar is a variable, omit the quotes, for instance if myvar = "2";
如果 myvar 是变量,则省略引号,例如 if myvar = "2";
then your selectors would be:那么您的选择器将是:
document.getElementById(myvar).innerHTML
For jQuery, use string concatenation:对于 jQuery,使用字符串连接:
$('#' + myvar).html();
document.getElementById
accepts a string argument which is the id of the element you'd like to select, so you won't need to include #, ie document.getElementById
接受一个字符串参数,它是你想要的元素的 id select,所以你不需要包括#,即
document.getElementById(myvar).innerHTML
Should work应该管用
Not directly related to your question, but it is invalid for an ID attribute to start with a number与你的问题没有直接关系,但ID属性以数字开头是无效的
http://www.w3.org/TR/html401/types.html#type-name http://www.w3.org/TR/html401/types.html#type-name
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后面可以跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号(“:”)和句点(“.”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.