簡體   English   中英

如何確定我是否單擊了標簽中的內容 <p> ?

[英]How to determine if I clicked on the content in a tag <p>?

我有一些html標記:

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

還有一個突出顯示所有標簽的功能(重要:我需要突出顯示所有標簽)和需要知道其是否為段落的類。

function myClass (input) {
    this.input = input;
    //on init
    init = function() {
        alert(input); //Point to determine if it is a paragraph
    };
    init();
};

$(function() {
    $("#content *").hover( function () {
        $(this).css("border", "1px solid blue");    //  style to mark (highlight) the tag
        return false;
    },
    function () {
        $(this).css("border", "none");  //  unmark the tag
    }).click( function () {
            var inst = new myClass($(this).html());
    });
});

如何找到我是否單擊了該段落,而不是其他標簽。

樣本http://jsfiddle.net/rvvbf4L1/1/

提前致謝。

在點擊處理程序中,您可以簡單地使用$(this).is('p')來測試所單擊的元素是否為段落。

jsFiddle示例

發生事件時,將創建一個事件對象。 從該事件對象,您可以獲得一些額外的信息。 例如,您可以單擊目標元素。

$('.selector').click(function(evtObj){
    if (evtObj.target.tagName === "P"){ // note the capital P
        // do stuff
    }
});

這是一個簡單的解決方案: http : //jsfiddle.net/1c1nr9sp/5/

$('p').on('click', function(){
    console.log('clicked on a paragraph');
});

請嘗試這個

$(function () {
    $("#content *").hover(function () {
        $(this).css("border", "1px solid blue"); // style to mark (highlight) the paragraph
        return false;
    },

    function () {
        $(this).css("border", "none"); //   unmark the paragraphs
    }).click(function (e) {
        var inst = new myClass(e.target.nodeName);
    });
});

我所做的更改是var inst = new myClass(e.target.nodeName);

參考

現場演示

我不知道這是不是您想要的,但是您去了!:

<!DOCTYPE html>
<html lang = 'es'>
    <head>
        <title> My Test </title>
        <style>
                p:hover{
                border: 1px solid black;
            }
        </style>
    </head>
    <body>
        <div id="content">
            <h3>Title</h3>
                <p>paragraph1</p>                                 
                <p>paragraph2</p>
                <p>paragraph3</p>
            <h3>Title</h3>
                <p>paragraph4</p>
                <p>paragraph5</p>
                <p>paragraph6</p>
        </div>
        <script type="text/javascript">
            var tagList = document.getElementsByTagName('p');
            var index;

            for(index in tagList){
                tagList[index].addEventListener('click', consoleMessage);
            }

            function consoleMessage(){
                console.log('Clicked on a paragraph');
                alert('Clicked on a paragraph');
            }
        </script>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM