Ответ 1
Да, вы можете выбрать только текстовое содержимое элемента, например:
var text = '';
$('a').contents().each(function(){
if(this.nodeType === 3){
text += this.wholeText;
}
});
$("#largemenutop").html(text);
Привет, ребята, это моя часть jQuery, которая делает мое меню для моих страниц.
function fetchmenus() {
$.getJSON('sys/classes/fetch.php?proccess=1', function(status) {
// get line status
$.each(status, function(i, item) {
if (item.id == "1") {
active = "class='active'";
lastpageid = item.href;
}
else {
active = "class='nonactive'";
}
$('<li id="' + item.href + '" ' + active + '><a href="#' + item.href + '">' + item.menuTitle + '<span class="menuspan" id="' + item.href + '"></span></a></li>').appendTo('#menuarea ul#mainmenu');
});
});
}
Что я хочу сделать, это получить item.menuTitle
в <a
, но перед <span>
В настоящее время я делаю так:
$('ul#mainmenu li').live('click', function(event) {
//alert(this.id);
$("li#" + lastpageid).removeClass();
fetchpage(this.id);
$("#largemenutop").html($(this).text());
$("li#" + this.id).addClass("active");
lastpageid = this.id;
});;
Есть ли лучший способ сделать это?
Да, вы можете выбрать только текстовое содержимое элемента, например:
var text = '';
$('a').contents().each(function(){
if(this.nodeType === 3){
text += this.wholeText;
}
});
$("#largemenutop").html(text);
Хорошее решение Herman, хотя оно может быть сведено к чему-то вроде этого:
$('li a').contents().filter(function() {
return this.nodeType == 3;
}).text();
<li><a href="#">Apple<span>hi</span> Juice</a></li>
Вернет Apple Juice
Fiddle: http://jsfiddle.net/49sHa/1/