2012-04-24 4 views
-1

Я делаю параллельный текст с подсветкой параллельного абзаца. Примерно на полпути, здесь: http://tinyurl.com/humecz2eАвтоматическое увеличение числа для редактирования html?

Проблема в том, что очень редко нужно вручную редактировать html, чтобы каждый абзац был окружен увеличивающимися числами. Например:

<div class="indented numbered"> 
<label class="p2"> 
Those who have denied the reality of moral distinc&shy;tions, may be ranked among the disingenuous disputants; nor is it conceivable, that any human creature could ever seriously believe, that all characters and actions were alike entitled to the<span class="epagno"></span> affection and regard of everyone. The difference, which nature has placed between one man and another, is so wide, and this difference is still so much farther widened, by education, example, and habit, that, where the opposite extremes come at once under our apprehension, there is no scepticism so scrupulous, and scarce any assurance so determined, as absolutely to deny all distinction between them. Let a man&rsquo;s insensibility be ever so great, he must often be touched with the images of <strong>right</strong> and <strong>wrong</strong>; and let his prejudices be ever so obstinate, he must observe, that others are susceptible of like impressions. The only way, therefore, of converting an antagonist of this kind, is to leave him to himself. For, finding that nobody keeps up the controversy with him, it is probable he will, at last, of himself, from mere weariness, come over to the side of common sense and reason. 
</label> 
</div> 

<div class="indented numberedlower"><div class="sbnumbered"> 
<label class="p3"> 
There has been a controversy started of late, much better worth examination, concerning the general foundation of <strong>morals</strong>; whether they be derived from <strong>reason</strong>, or from <strong>sentiment</strong>; whether we attain the knowledge of them by a chain of argument and induction, or by an immediate feeling and finer internal sense; whether, like all sound judgment of truth and falsehood, they should be the same to every rational intelligent being; or whether, like the perception of beauty and deformity, they be founded entirely on the particular fabric and constitution of the human species. 
</label> 
</div></div> 

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

Любая помощь будет оценена по достоинству. Благодаря!

+0

Вы ищете [CSS-счетчики] (https: // deve loper.mozilla.org/en/CSS_Counters)? – user123444555621

+0

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

+0

@ Pumbaa80 Нет, я так не думаю. Цифры должны быть записаны в сам html. – 97847658

ответ

1

Вы хотите использовать Javascript:

<script type="text/javascript"> 
    var elements = document.getElementsByTagName('label'); 
    for (var i in elements) { 
     var elem = elements[i]; 
     elem.className += " p"+i; 
    } 
</script> 

Вы могли бы рассмотреть возможность использования уникальных идентификаторов вместо уникальных имен классов:

<script type="text/javascript"> 
    var elements = document.getElementsByTagName('label'); 
    for (var i in elements) { 
     var elem = elements[i]; 
     elem.id = "p"+i; 
    } 
</script> 

Если вы просто хотите, чтобы стиль этикетки иначе, вам можно попробовать использовать селектор CSS nth-child:

<style type="text/css"> 
    div label:nth-child(odd) { 
     background-color: red; 
    } 

    div label:nth-child(even) { 
     background-color: blue; 
    } 
</style> 
+0

Я мало знаю о Javascript, но мне интересно, можно ли его использовать для изменения самого html и соответствует ли это тому факту, что эти два языка не всегда соответствуют их абзацу. Благодаря! – 97847658

+0

Javascript оценивается браузером при визуализации страницы. Поэтому классы не будут записываться в ваши .html-файлы, однако при загрузке страницы браузер выполнит Javascript и динамически напишет в значениях класса для указанных элементов. – twaddington

Смежные вопросы