2011-10-24 42 views
0

我正在構建一個交互式表單並根據用戶的回答加載字段。現在我只有兩種物體「輸入收音機」和「textarea」。當我通過JQuery獲得答案的價值時,我怎麼能知道我在最後加載的字段集內處理了什麼對象?JQuery:如何知道我們正在處理的表單對象的類型?

這就是我想:

$.fn.getNodeName = function() { // returns the nodeName of the first matched element, or "" 
    return this[0] ? this[0].nodeName : ""; 
}; 

//var $something = $('input[type=radio]:checked:last'); 
var $something = $('fieldset:last').parent('nth-child(2)'); 

//$('#news ul li:first-child').addClass('active'); 

alert($something.getNodeName()); 

但它不工作... 感謝。

+0

「':radio'」不是在CSS現有pseudoselector 。也許你打算爲該部分使用一個屬性選擇器,例如'輸入[類型=無線電]:檢查:last'? –

+0

已更新的問題@Jordan – Roger

回答

2

我已經擴展你的jQuery函數也返回type,當元素是一個input元素:

$.fn.getNodeName = function() { 
    var elem = this[0]; //Get the first element of the jQuery object 
    if(!elem) return ""; 
    var name = elem.nodeName.toLowerCase(); 
    return name == "input" ? "input[type=" + elem.type + "]" : name; 
}; 

可能的返回值的例子:
textareainput[type=text]input[type=button] ...

如果您更喜歡其他輸出格式,請調整該功能。指定類型的另一種方法是通過添加額外的屬性設置爲返回值,如:

$.fn.getNodeName = function() { 
    var elem = this[0]; //Get the first element of the jQuery object 
    if (!elem) return ""; 
    var name = elem.nodeName.toLowerCase(); 
    if (name == "input") { 
     name.type = elem.type; 
    } 
    return name; 
}; 
+0

這是一個答案!非常感謝你。 – Roger

相關問題