2017-07-14 65 views
1

我有一個輸入類,我想將其更改爲選擇表單屬性。jQuery根據屬性更改值

到目前爲止,我有類似的工作在我的h2.title上,將單詞從Apple更改爲Orange。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script type="text/javascript"> 
if(){ 
    $(document).ready(function(){ 
     $(document).live({ 
      mouseover: function(e) { 
      $('h2.title').each(function() { 
       var text = $(this).text(); 
       text = text.replace('Apple', 'Orange'); 
       $(this).text(text);   
      }); 
      } 
     }); 
    }); 
} 
</script> 

而且我真的很喜歡這個轉換,選擇表格屬性

<input class = "form-input ng-pristine ng-untouched ng-valid ng-empty ng valid-maxlength" id="Banana" maxlength = "2000" name="Banana" type=text" 

有沒有辦法上班這件事? 2個選擇選項

+0

格式的代碼,讓我們讀更好的 –

回答

1

是的,你可以這樣做:

text = text.replace('Apple', $(this).attr("name")); 

這裏是一個演示:

$(document).ready(function() { 
 
    $(document).on("mouseover", function(e) { 
 
    $('h2.title').each(function() { 
 
     var text = $(this).text(); 
 
     text = text.replace('Apple', $(this).attr("name")); 
 
     $(this).text(text); 
 
    }); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h2 class="title" name="Banana">Apple</h2> 
 
<h2 class="title" name="Orange">Apple</h2> 
 
<h2 class="title" name="Pineapple">Apple</h2> 
 
<h2 class="title" name="Grape">Apple</h2>

+0

謝謝非常多Racil –

+0

爲簡潔起見,我建議進一步移動:'$('h2.title')。text(function(index,currentText){return currentText.r eplace('Apple',this.name); });使用'each()'和多次調用'text()'方法,更不用說使用'$(this).attr('name')',所做的工作遠不止於必要。 –

+0

@DavidThomas對「簡潔」達成了一致,但我保留原來的代碼,因爲它可能更容易實現OP(即個人編碼風格)。至於「更多的工作」,我不明白你的建議可以減少工作或減少對「text()」的調用。我的回答和你建議的代碼都會調用'text()'兩次,一次獲得值,另一次設置它(儘管這在代碼中是隱含的)。而你所建議的'name'屬性只能用於'input'元素,而不是'h2'。 –