如何使用JQuery选择几个段落?

时间:2015-07-26 19:54:57

标签: javascript jquery html css

我有som HTML:

<div id="content">
    <p>paragraph1</p>                                 
    <p>paragraph2</p>
    <p>paragraph3</p>
    <p>paragraph4</p>
    <p>paragraph5</p>
    <p>paragraph6</p>
</div>

JQuery函数选择其中一段:

$(function() {
    $("#content *").hover( function () {
        $(this).css("border", "1px solid blue");
        return false;
    },
    function () {
        $(this).css("border", "none");  //  unmark the paragraphs
    }).click( function (evtObj) {
         //make action with selected paragraph
        };
    });
});

示例:http://jsfiddle.net/rvvbf4L1/6/

如何通过鼠标选择几个段落并获取其内部HTML? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以将cssjQuery一起使用,而不是使用悬停。然后添加和删除selected类。这也可以让你对可能证明有用的所有段落$('p.seleted').each(function () {})

风格

<style>
p.selected {
    border: 1px solid blue;
}

p:hover {
   border: 1px dotted blue; 
}
</style>

切换类并调用新的myClass

$("#content *").click( function () {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
    } else {
        $(this).addClass('selected');
        var allHtml = ""; 
        $("p.selected").each(function () {
            allHtml += " " + $(this).html(); 
        });
        var inst = new myClass(allHtml);

    }
});

请参阅fiddle

答案 1 :(得分:-1)

我通过将你的html粘贴到一个空白文本文件中进行了快速测试。如果您不包含jQuery库,则不会获得多个结果。尝试使用以下html的jQuery代码:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
<body>
<div id="content">
    <p>paragraph1</p>                                 
    <p>paragraph2</p>
    <p>paragraph3</p>
    <p>paragraph4</p>
    <p>paragraph5</p>
    <p>paragraph6</p>
</div>
</body>
<html>