2015-03-21 5 views
0

У меня есть этот текст внутри BLOCKQUOTE:Jquery добавить тег внутри BLOCKQUOTE перед тегом

<blockquote class="tr_bq"> 
4 Text<br /> 
20 TExt<br /> 
2 Another text a little longer<br /> 
<br /> 
20 text</blockquote> 

Я хочу добавить для каждой строки в тег или преобразовать бр включить класс. если бр включал всю строку, я бы знал, как это сделать. Это, как я хочу закончить, как:

<blockquote class="tr_bq"> 
<strike>4 Text</strike><br/> 
<strike>20 TExt</strike><br/> 
<strike>2 Another text a little longer</strike><br/> 
<br /> 
<strike>20 text</strike></blockquote> 

или

<blockquote class="tr_bq"> 
<br class="X">4 Text<br> 
<br class="X">20 TExt<br> 
<br class="X">2 Another text a little longer<br> 
<br /> 
<br class="X"> 20 text</br></blockquote> 

Я попытался с обручем, но без Sucess, любой способ сделать это?

+0

Пожалуйста, обратите внимание, что ''
является самостоятельным теге. – Itay

ответ

1

Вы можете сделать это, манипулируя внутренним HTML-блоком.

$('.tr_bq').each(function() { 
    var html = $(this).html(); 
    var newHtml = html.split('<br>').map(function (str) { 
     return '<strike>' + str + '</strike>'; 
    }).join('<br>'); 
    $(this).html(newHtml); 
}); 
+0

Я могу понять код, и мне кажется, что это нормально, но я пробовал без каких-либо результатов. –

+0

@ JoséMoreira В каком браузере? Я пытался в Chrome. – GregL

+0

только пробовал в firefox. –

1

Просто предложить некрасивая JavaScript средства достижения этой цели, избегая (ненужное) использование библиотеки:

function wrapNodesWith(nodes, tag) { 
    // if we have neither nodes to wrap, nor a tag to wrap 
    // them with, we quit here: 
    if (!nodes || !tag) { 
    return false; 
    } 

    // otherwise: 

    // we convert the nodes to an array (using Array.prototype.slice, 
    // in conjunction with Function.prototype.call): 
    nodes = Array.prototype.slice.call(nodes, 0); 

    // if the tag parameter passed to the function is a string ('strike'), 
    // we create that element using document.createElement(tag), 
    // otherwise we assume we've got an HTMLElement (this is a very 
    // naive check) and so we use that: 
    tag = 'string' === typeof tag ? document.createElement(tag) : tag; 

    // an unitialised variable for use within the following forEach: 
    var clone; 

    nodes.forEach(function(n) { 
    // n is the node over which we're iterating, 

    // cloning the tag (to avoid multiple calls 
    // to document.createElement): 
    clone = tag.cloneNode(); 

    // setting the textContent of the clone to the nodeValue 
    // of the node (if it's a textNode), or to the textContent of 
    // element (again a simple check): 
    clone.textContent = n.nodeType === 3 ? n.nodeValue : n.textContent; 

    // replacing the childNode, using parentNode.replaceChild(), 
    // inserting clone and removing n: 
    n.parentNode.replaceChild(clone, n); 
    }); 

} 

// finding the first <blockquote> element: 
var blockquote = document.querySelector('blockquote'), 
    // creating an array of the childNodes of the <blockquote>: 
    children = Array.prototype.slice.call(blockquote.childNodes, 0), 
    // filtering the children array, retaining only those nodes for 
    // which the assessment returns true: 
    textNodes = children.filter(function(n) { 
     return n.nodeType === 3; 
    }); 

// can be called with: 
wrapNodesWith(textNodes, 'strike'); 

// or: 
wrapNodesWith(textNodes, document.createElement('strike')); 

function wrapNodesWith(nodes, tag) { 
 
    if (!nodes || !tag) { 
 
    return false; 
 
    } 
 

 
    nodes = Array.prototype.slice.call(nodes, 0); 
 
    tag = 'string' === typeof tag ? document.createElement(tag) : tag; 
 

 
    var parent, clone; 
 

 
    nodes.forEach(function(n) { 
 
    clone = tag.cloneNode(); 
 
    clone.textContent = n.nodeType === 3 ? n.nodeValue : n.textContent; 
 
    n.parentNode.replaceChild(clone, n); 
 
    }); 
 

 
} 
 

 
var blockquote = document.querySelector('blockquote'), 
 
    children = Array.prototype.slice.call(blockquote.childNodes, 0), 
 
    textNodes = children.filter(function(n) { 
 
    return n.nodeType === 3; 
 
    }); 
 

 
wrapNodesWith(textNodes, 'strike');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<blockquote class="tr_bq"> 
 
    4 Text 
 
    <br />20 TExt 
 
    <br />2 Another text a little longer 
 
    <br /> 
 
    <br />20 text 
 
</blockquote>

Ссылки:

+0

Ну, я не знаю, реализую ли я это неправильно, но он, похоже, не работал. –

+0

Работает ли он во включенном фрагменте? И как вы его используете, можете ли вы связать меня с простой демонстрацией [JS Fiddle] (http://jsFiddle.net/), чтобы показать мне? –

+0

во включенном фрагменте он работает, но после этого мне удалось найти способ работать только с javascript. Но спасибо за ваше время, тем не менее, это было полезно. –

0

Ну,

я сумел заставить его работать с этим:

var pre = document.getElementsByTagName('blockquote'),pl = pre.length; 
    for (var i = 0; i < pl; i++) { 
    var pro = pre[i].innerHTML.split(/<br>/), pz = pro.length; 
    pre[i].innerHTML = ''; 
    for (var a=0; a < pz ; a++) { 
    pre[i].innerHTML += '<strike>' + pro[a] + '</strike><br/>'; 
    } 
    } 
Смежные вопросы