可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to get the menu name when user is click.
<a class="menu" onclick="getMenu()" href="#"> Home </a> <a class="menu" onclick="getMenu()" href="#"> About</a> <a class="menu" onclick="getMenu()" href="#"> Contact</a>
So in this function the alert name will popup.
function getMenu(){ //the code declare here alert('is click'); }
The expected result Home is click / Contact is click
回答1:
If you would like a jQuery method....
You don't need the onclick
attribute
this
- The element used to trigger the function
.textContent
- The text content of the element
.trim()
- Remove white spaces
this.textContent.trim()
Element > text content > trim
$('.menu').click(function(){ alert(this.textContent.trim()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="menu" href="#"> Home </a> <a class="menu" href="#"> About</a> <a class="menu" href="#"> Contact</a>
I hope this helps. Happy coding!
回答2:
Pass clicked element object to the function:
<a class="menu" onclick="getMenu(this)" href="#"> Home </a>
and then read textContent
or innerHTML
property of it:
function getMenu(obj) { alert(obj.textContent); }
Also you might want to trim out white spaces around the text:
obj.textContent.trim();
Check the demo below.
function getMenu(obj) { alert(obj.textContent.trim()); }
<a class="menu" onclick="getMenu(this)" href="#"> Home </a> <a class="menu" onclick="getMenu(this)" href="#"> About</a> <a class="menu" onclick="getMenu(this)" href="#"> Contact</a>
回答3:
Like so, pass this
(refers to current element) to your function getMenu
, and to get content from links you can use .innerHTML.
function getMenu(el) { alert(el.innerHTML + ' is click'); }
<a class="menu" onclick="getMenu(this)" href="#"> Home </a> <a class="menu" onclick="getMenu(this)" href="#"> About</a> <a class="menu" onclick="getMenu(this)" href="#"> Contact</a>
also you can use .textContent
for get inner text, but be aware IE lower than 9 does not support it, also there is .innerText
but FF does not support it, you can use small workaround to get inner text in all bworsers, like so
alert((el.innerText || el.textContent) + ' is click');
回答4:
Use a cleaner way as you are using jQuery:
<a class="menu" id="1" href="#"> Home </a> <a class="menu" id="2" href="#"> About</a> <a class="menu" id="3" href="#"> Contact</a> <script> $(".menu").click(function(){ var currentId = $(this).attr("id"); alert($.trim($("#"+currentId).text())); }); </script>
$(".menu").click(function(){ var currentId = $(this).attr("id"); alert($.trim($("#"+currentId).text())); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a class="menu" id="1" href="#"> Home </a> <a class="menu" id="2" href="#"> About</a> <a class="menu" id="3" href="#"> Contact</a>