点击链接的文字 [英] 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中:
In my 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.
};
我该如何实现?
推荐答案
您可以将当前链接作为参数传递给函数:
You could pass the current link as argument to the function:
<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
属性获取其中的文本:
and then use the innerHTML
property to fetch the text inside:
var myFunc = function (link) {
alert(link.innerHTML);
};
更新:
UPDATE:
我没有注意到实际上您的问题是用jQuery标记的.在这种情况下,我建议您毫不客气地订阅点击处理程序:
I haven't noticed that actually your question is tagged with jQuery. In this case I would recommend you unobtrusively subscribing to the click handler:
<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文件中:
and in a separate js file:
$(function() {
$('.Buttons a').click(function() {
alert($(this).text());
return false;
});
});
更新2:
UPDATE 2:
有人问如果这些锚是动态生成的,如何分配这些点击处理程序.因此,假设您从以下标记开始:
It was asked how to assign those click handlers if those anchors were dynamically generated. So let's assume that you start with the following markup:
<ul class="Buttons"></ul>
,然后在发生某些事件(单击或类似事件)时,动态添加锚点:
and then when some event happens (click or something) you add an anchor dynamically:
$('<li/>', {
html: $('<a/>', {
href: '#',
text: 'some text ....',
click: myFunc
})
}).appendTo('.Buttons');
您在某处定义了myFunc
的位置:
where you have defined myFunc
somewhere:
var myFunc = function() {
alert($(this).text());
return false;
}
这篇关于点击链接的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!