Я новичок в JQuery и с вопросом, который может сбить с толку. Но большое спасибо за проверку этого. Я хочу изменить текст внутри элемента. например:
<div class="testit">test it for no.1 and test.com <img=...> <a href="http://test.com/">test it</a></div>
<div class="testit">another test for No.2 and test2.com and test.com <img=...> <a href="http://test2.com/">test2</a> Another description</div>
Я хотел бы использовать JQuery для изменения части "некоторых текстовых коннектов" в каждом классе "testit", но я хочу сохранить остальные теги без изменений. Например: желаемый результат будет:
<div class="testit">test it for no.1 and <a href="http://test.com">test.com</a> <img=...> <a href="http://test.com">test it</a></div>
<div class="testit">another test for No.2 and <a href="http://test2.com">test2.com</a> and <a href="http://test.com">test.com</a> <img=...> <a href="http://test2.com/">test2</a> Another description</div>
Следующее JQuery может получить исходное содержимое, но не может их модифицировать. Можете ли вы посоветовать мне, как изменить программу jquery?
var getTextNodesIn = function(el) {
return jQuery(el).find().andSelf().contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
});};
var current_text=getTextNodesIn(this);
current_text.text('new contents here');
Добавлено Regex, чтобы определить, содержит ли строка значение
var count = 1;
$('.testit').each(function () {
//check if the test string is found
var str = $(this).text();
var patt = new RegExp("test.com");
var res = patt.test(str);
if(res){
$(this).text("new text contents No." + count);
count++;
}
});
jQuery(el).find().andSelf()
наjQuery(el)
. Вызов.find
без аргумента возвращает пустой объект jQuery.current_text[0].nodeValue
Если у вас есть много узлов, проходите через них и устанавливаете его. jsfiddle.net/DJ8j6