JavaScript中給onclick繫結事件後return false遇到的問題
阿新 • • 發佈:2019-02-05
處理return false失效問題,如:
<p><a href="a.jpg" title="hao" onclick="showPic(this);return false;">點選</a</p>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>title</title> </head> <body> <script type="text/javascript"> function showPic(hao){ var source = hao.getAttribute("href"); var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src", source); var text = hao.getAttribute("title"); var description = document.getElementById("description");//獲取目標 description.firstChild.nodeValue = text; return false;//加上 } </script> <div><p id="a">我來了</p></div> <!--這裡雖然設定了return false,但是點選後,沒有達到我想要的效果,還是跳轉了, 目的是設定了return false的話,自然是返回false時,不跳轉的。 細想下的話,就會發現return false;並不是像我想的那樣把結果值返回給onclick了。 於是,這裡就需要改動了,要把函式showPic的結果值返回給onclick才可以。這樣的話,就要在 函式最後返回false即可,如:return false;//加上 <p><a href="a.jpg" title="hao" onclick="showPic(this);return false;">點選</a</p> --> <!--改動後,完好地處理了return false失效問題--> <p><a href="a.jpg" title="hao" onclick="return showPic(this);">點選</a> </p> <img id="placeholder" src="bg.jpg" alt="my image gallery" /> <p id="description">Choose an image.</p> </body> </html>
小記錄