簡體   English   中英

點擊鏈接的文字

[英]Text of the clicked link

<ul class="Buttons">
    <li><a href="#" onclick="myFunc(); return false;">Accept</a></li>
    <li><a href="#" onclick="myFunc(); return false;">Reject</a></li>
    <li><a href="#" onclick="myFunc(); return false;">On Hold</a></li>
    <li><a href="#" onclick="myFunc(); return false;">Completed</a></li>
</ul>

在我的script.js中:

var myFunc = function () {
    // I want to get the Text of the link e.g. if the first list item link is
    // clicked, store "Accept" in a variable.
};

我怎樣才能做到這一點?

您可以將當前鏈接作為參數傳遞給函數:

<ul class="Buttons">
    <li><a href="#" onclick="myFunc(this); return false;">Accept</a></li>
    <li><a href="#" onclick="myFunc(this); return false;">Reject</a></li>
    <li><a href="#" onclick="myFunc(this); return false;">On Hold</a></li>
    <li><a href="#" onclick="myFunc(this); return false;">Completed</a></li>
</ul>

然后使用innerHTML屬性獲取里面的文本:

var myFunc = function (link) {
    alert(link.innerHTML);
};

更新:

我沒注意到你的問題實際上是用jQuery標記的。 在這種情況下,我會建議你不引人注意地訂閱點擊處理程序:

<ul class="Buttons">
    <li><a href="#">Accept</a></li>
    <li><a href="#">Reject</a></li>
    <li><a href="#">On Hold</a></li>
    <li><a href="#">Completed</a></li>
</ul>

並在一個單獨的js文件中:

$(function() {
    $('.Buttons a').click(function() {
        alert($(this).text());
        return false;
    });
});

更新2:

有人詢問如果動態生成這些錨點,如何分配這些點擊處理程序。 因此,我們假設您從以下標記開始:

<ul class="Buttons"></ul>

然后當某些事件發生時(點擊或其他)你動態添加一個錨:

$('<li/>', {
    html: $('<a/>', {
        href: '#',
        text: 'some text ....',
        click: myFunc
    })
}).appendTo('.Buttons');

你在哪里定義了myFunc

var myFunc = function() {
    alert($(this).text());
    return false;
}

既然你似乎在使用jQuery ......

$("ul.buttons > li > a").click(function () {
  alert( $(this).text() );

  myFunc(this);
  return false;
});

... 刪除那些onclick處理程序。 ;)

    $('.Buttons li a').click(function(event) {
       var myVariable = $(this).text();
        alert(myVariable);
        event.preventDefault();
    });
$(function(){ $('.Buttons').click(function(){ alert($(this).html(); }) })

如果您正在使用jQuery,那么您可以綁定到這樣的元素:

//wait for document.ready to fire
$(function () {

    //find the links in the `.Button` list and bind a click event handler to them
    $('.Buttons').find('a').on('click', function () {

        //alert the text of the clicked element
        alert($(this).text());

        //prevent the normal behavior of the link, also stop the propagation of the event so no other elements fire event handlers for this event
        return false;
    });
});

請注意.on()是jQuery 1.7中的新增內容,在這種情況下與使用.bind()相同: http//api.jquery.com/on

然后你的HTML里面不需要任何JS:

<ul class="Buttons">
    <li><a href="#">Accept</a></li>
    <li><a href="#">Reject</a></li>
    <li><a href="#">On Hold</a></li>
    <li><a href="#">Completed</a></li>
</ul>

$(this).text()應該適合你。

暫無
暫無

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

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