[英]How to check element type in javascript
I have a situation in which i want to convert a <select>
tag into a <input type="text">
and <input type="text">
into <select>
bu using some condition. 我有一种情况,我想使用一些条件将<select>
标签转换为<input type="text">
和<input type="text">
到<select>
bu。 So how can i know that this element a type text or type select using id attribute. 那么我怎么知道这个元素是一个类型文本或类型选择使用id属性。
And also a pure javascript solution: 还有一个纯粹的JavaScript解决方案:
function toggle(a){
if(a.tagName === 'INPUT'){
a.outerHTML = '<select id="toggle"></select>';
}else{
a.outerHTML = '<input type="text" id="toggle"/>'
}
}
http://jsfiddle.net/M6qXZ/1/ http://jsfiddle.net/M6qXZ/1/
e => e.outerHTML = e.tagName === "INPUT" ? "<select id='toggle'></select>" : "<input id='toggle'/>"
By using 通过使用
$("#inputID").attr("type");
If you alert above you will get the type of input element, then you can apply checks accordingly. 如果您在上面提醒您将获得输入元素的类型,那么您可以相应地应用检查。
Ref here : http://api.jquery.com/attr/ 请参考: http : //api.jquery.com/attr/
UPDATE UPDATE
check using 检查使用
if(!$("#inputID").is("select")) {
// the input field is not a select
}
got from a link while searching not tested though. 虽然搜索未经测试但从链接获得。
Get the element type using jQuery: 使用jQuery获取元素类型:
var elementType = $("#myid").prop('tagName');
Get the input type attribute using jQuery: 使用jQuery获取输入类型属性:
var inputType = $("#myid").attr('type');
例如,condicion可能是:
if($('#whateverid').attr('type') == "text")
You can use .is() to test whether the elements is of type x like 您可以使用.is()来测试元素是否类似于x
Use :text selector to test for text input element 使用:文本选择器来测试文本输入元素
if($("#inputID").is(":text")){
//to test for text type
}
Use element selector to test for select element 使用元素选择器测试select元素
if($("#inputID").is("select")){
//to test for select
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.