简体   繁体   English

jQuery可以从字符串变量中的HTML标记中获取属性

[英]Can jQuery get an attribute from an HTML tag in a string variable

Inside JavaScript, At runtime I am getting HTML code for checkbox inside a string as follows: 在JavaScript中,在运行时我在string获取checkbox HTML代码,如下所示:

var chk="<input type='checkbox' id='checkbox1' name='chk1' />";

I want to get the ID of the checkbox . 我想获取checkboxID

My Question is: 我的问题是:

Does jquery support any api to to retrive value of id ? jquery是否支持任何api来检索id值?
Or 要么
Do I have to follow the JavaScript api to achieve the same? 我是否必须遵循JavaScript api来实现相同的目标?

Note: Currently I am using following JavaScript code: 注意:目前我正在使用以下JavaScript代码:

var i=chk.indexOf("id");
var s=chk.substring((i+4));
var j=s.indexOf("'");
s=s.substring(0,j);

Finally s contains id of checkbox . 最后s包含checkbox id

Try this, 尝试这个,

Live Demo 现场演示

var chk = $("<input type='checkbox' id='checkbox1' name='chk1' />");

alert(chk.attr('id'));​

Yes, you can do it easily with jquery, as follows: 是的,您可以使用jquery轻松完成,如下所示:

var chk="<input type='checkbox' id='checkbox1' name='chk1' />";
id = $(chk).attr('id');
alert(id); //alerts 'checkbox1'

See working demo 看工作演示

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

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