简体   繁体   English

根据换行符使用jQuery选择段落中的行

[英]Select line in paragraph using jQuery based on line break

This question may be related. 这个问题可能是相关的。

I have a Django recipe app that uses a form containing of a CharField TextArea. 我有一个Django食谱应用程序,该应用程序使用包含CharField TextArea的形式。 This field is used to enter a list of directions (string). 此字段用于输入方向列表(字符串)。 I have chosen to separate each direction with a line break (ENTER in form), and use the following in my template (html) to keep line breaks as in original form 我选择用换行符(在表单中为ENTER)分隔每个方向,并在模板(html)中使用以下内容以使换行符保持原始形式

<div id="items">
    <p> 
        {{ recipe.directions_field|safe }}
    </p>
</div>

This will basically appear as something like 这基本上会像

<div id="items">
    <p>
        Line one <br/>
        Two <br/> 
        Three <br/>
    </p>
</div>

What I want to do is to use jQuery to "check" (strikethrough) one single line (may contain of several words) in my template. 我想做的是使用jQuery在模板中“检查”(删除线)一行(可能包含多个单词)。 I have tried the following, but as expected, this checks the entire paragraph. 我尝试了以下内容,但是正如预期的那样,这将检查整个段落。

<script>
  $(document).ready(function() {
    $("#items p").click(function () {
    $(this).toggleClass('stroked');
    });
  });
</script> 

Where my css has 我的css在哪里

.stroked{ text-decoration: line-through; }

In my Django view I replaced "\\n" with html line break in order to make sure line breaks are not removed when shown in template. 在我的Django视图中,我将“ \\ n”替换为html换行符,以确保在模板中显示时不删除换行符。

directions = directions.replace("\n", "<br/>")

I think a solution like this would work if I could just find an easy way to use <br/> as a splitter instead of ". " or any other symbol. 我觉得像一个解决这个 ,如果我可以随便找个用一种简单的方式将工作<br/>作为一个分离器,而不是“”或任何其他标志。 I couldn't make that work with <br/> in the example. 在示例中,我无法使用<br/>进行处理。

Any suggestions, either using a solution like this or another way? 有什么建议,或者使用的溶液等这样或另一种方式? I guess there are many ways to solve this, but hope to find an easy implementation. 我想有很多方法可以解决这个问题,但是希望找到一个简单的实现。

Thanks for any reply. 感谢您的答复。

It's much easier if you wrap every single line into <span></span> , like this: 如果将每一行都包装到<span></span> ,则更加容易,如下所示:

<div id="items">
<p>
    <span>line one <br/></span>
    <span>line two <br/></span>
    <span>line three <br/></span>
</p>
</div>

So what you need to do in javascript is: 因此,您需要在javascript中做的是:

$(function(){
    $('#items > p > span').click(function(){
        if($(this).attr('class') == 'stroked'){
            $(this).removeAttr('class');
        }
        else{
            $(this).addClass('stroked');
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM