javascript HTML 如何在用户单击句子时提示消息框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19048580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML How to prompt a Message Box when the User clicks a sentence
提问by Andrew Smith
I have the simple text: "What is this?" on a HTML page.
我有简单的文字:“这是什么?” 在 HTML 页面上。
Without making it a button, is there a way to simply prompt a message box when the user clicks the text?
如果不让它成为按钮,有没有办法在用户单击文本时简单地提示一个消息框?
回答by That Brazilian Guy
The simplest way is using Javascript:
最简单的方法是使用 Javascript:
<a href="#" onClick="alert('Hello World!');">What is this</a>
(The #
will make the page jump to the top after the click, but there are ways to prevent it, and some will discourage its usage. The JavaScript can be put on the href
as well, but it's not considered good practice.)
(#
点击后会使页面跳转到顶部,但有一些方法可以防止它,有些会阻止它的使用。JavaScript也可以放在上面href
,但不是很好的做法。)
But it doesn't necessarily needto be a <a>
anchor, it can be any HTML element:
但它不一定需要是一个<a>
锚点,它可以是任何 HTML 元素:
<span onClick="alert('Hello World!');">What is this</span>
If it is not a <a>
, <button>
or any other element where it is usual to indicate user interaction, you need to stilize it or otherwise indicate it is clickable somehow.
如果它不是<a>
,<button>
或者,通常指示用户交互的任何其他元素,你需要stilize或以其他方式表明它是可点击莫名其妙。
回答by Stanislav Ryahov
You can add click handler to any element, not only a button.
您可以将单击处理程序添加到任何元素,而不仅仅是按钮。
<span onclick="showMsg()">What is this?</span>
回答by Guest
This is a good JavaScript way of doing it:
这是一个很好的 JavaScript 方法:
`<script language=JavaScript>
<a href = "#" onMouseOver=" alert("THIS IS SPARTA!!");"> What is this? </a>"
</script>`
Make sure to put this within the body of the html.
确保将其放在 html 的正文中。