2011-10-12 18 views
1

我目前正在試圖用jquery操縱兩種不同類型的控件(標籤和輸入)的內容。截至目前,我正在通過使用兩個命令來做到這一點。需要一個結合val()和text()的命令

if(true) 
{ 
    myControl.text('@types.Text'); 
    myControl.val('@types.Text'); 
} 

是否有一個命令都可以做?

附註:我已經試過了HTML()和append(),但我覺得這些都是對文本()和Val()

+0

什麼'myControl.text( '@ types.Text')|| myControl.val( '@ types.Text')'? –

回答

3

我用這樣的事情在我的JavaScript公用事業

$.fn.setValue = function(val) { 
    return this.each(function() { 
     switch (this.tagName.toLowerCase()) { 
      case "input": 
       switch ($(this).attr("type").toLowerCase()) { 
        case "hidden": 
        case "password": 
        case "text": 
         $(this).val(val); break; 
        case "radio": 
        case "checkbox": 
         this.checked = val; break; 
       } break; 
      case "span": 
      case "button": 
      case "label": 
       $(this).html(val); break; 
      case "select": 
      case "textarea": 
       $(this).val(val); break; 
     } 
    }); 
}; 

然後你可以使用你的新功能有沒有幾乎任何類型的元素不必擔心它是什麼。

var myControl = $('#someSelector'); 
myControl.setValue('@Types.text'); 
+0

很棒的回答。我做的只是將按鈕移動到輸入部分。我不確定長遠來看這是否會更好,但對我來說這很有效。 –

+1

@dan_vitch:很好,我錯過了「輸入」部分的「按鈕」類型。底部的「按鈕」情況用於'

0

沒有命令與val()結合text()變化。爲此編寫自定義函數有什麼問題嗎?順便說一句:雖然text()html()幾乎相同,val()append()是非常不同的 - 檢查jQuery文檔。

2

你可以寫你自己的,是這樣的:

$.fn.tval = function (value) { 
    if (this.is(':input:not(:checkbox):not(:radio)')) { 
     this.val(value); 
    } 
    else { 
     this.text(value); 
    } 
    return this; 
} 
0

,如果你也想支持VAL(的get側)和文本():

$.fn.tval = function(value) { 
    if (value) { 
     if (this.is(':input:not(:checkbox):not(:radio)')) { 
      this.val(value); 
     } else { 
      this.text(value); 
     } 
     return this; 
    }else{ 
     if (this.is(':input:not(:checkbox):not(:radio)')) { 
      return this.val(); 
     } else { 
      return this.text(); 
     } 
    } 
}