2012-12-30 146 views
1

從下面的HTML中,我想用jQuery獲取<label></label>中的文本,但排除標籤中跨度內的文本。用jQuery獲取標籤內的文本

<label for="name">Name<span class="required">Required</span></label> 
<input type="text" class="requiredField" name="name" /> 

我嘗試以下操作:

jQuery('.requiredField').each(function() { 
    var labelText = jQuery(this).prev().text(); 
} 

它接收這是跨度.required內部以及文字,但我想唯一的「名稱」(即NameRequired)。我怎樣才能排除這一點?謝謝。

+1

可能的重複[在元素中獲取文本不包括被繼承人](http://stackoverflow.com/questions/6487777/getting-text-within-element-excluding-decendants) –

+1

使用更多ID ... –

+0

你有沒有知道你只需要以長格式編寫'jQuery'一次?通過將代碼封裝在'(function($){....})(jQuery);'中,無論是否使用了noConflict,都可以使用'$'。 – ThiefMaster

回答

1

這應該工作:

jQuery('.requiredField').each(function() { 
    labelTextCopy = jQuery(this).prev().clone(); 
    copyChild = labelTextCopy.children(); 
    copyChild.remove(); 
    console.log(labelTextCopy.text()); 
})​ 

的jsfiddle:http://jsfiddle.net/5xRLg/5/

2

的有效方法:
創建fn,你可以一次又一次地打電話,而不是做cloneremove每一個地方:

jQuery.fn.onlyText = function() { 
    return this 
      .clone() 
      .children() 
      .remove() 
      .end() 
      .text(); 
}; 

// And then your code 

jQuery('.requiredField').each(function() { 
    var labelText = jQuery(this).prev().onlyText(); 
}); 

http://jsfiddle.net/OMS_/x7xPB/