2014-01-22 69 views
0

我正在努力使用正確的語法來更改您使用javascript進行onclick的鏈接。javascript/html:如何使用document.getElementById更改onclick = location.herf

我:

JS:

function changeLink { 
link = "page2.php"; 
document.getElementById('go').onclick= function() { location.href(link); }; 
} 

HTML:

<button type="submit" name="submit1" style="width:100%;height:30px" onclick="changeLink();">Change Place To Go</button> 
<div id="go" onclick="document.location.href='page1.php';">Click to go somewhere</div> 

JS fiddle

感謝您的任何建議!

回答

1

讓我們先從一些common.js

//<![CDATA[ 
var doc = document, bod = doc.body; 
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]); 
bod.className = 'js'; 
function gteIE(version, className){ 
    if(IE >= version){ 
    bod.className = className; 
    } 
} 
function E(e){ 
    return doc.getElementById(e); 
} 
//]]> 

現在讓我們做你的主頁,index.php

//<![CDATA[ 
function direct(id, link){ 
    E(id).onclick = function(){ 
    location = link; 
    } 
} 
direct('button1', 'page1.php'); direct('button2', 'page1.php'); 
//]]> 

HTML可以看起來更像:

<!DOCTYPE html> 
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> 
    <head> 
    <meta http-equiv='content-type' content='text/html;charset=utf-8' /> 
    <style type='text/css'> 
     @import 'common.css'; @import 'index.css'; 
    </style> 
    </head> 
<body class='njs'> 
    <div id='main'> 
    <input type='button' id='button1' value='button 1' /> 
    <input type='button' id='button2' value='button 2' /> 
    </div> 
    <script type='text/javascript' src='common.js'></script> 
    <script type='text/javascript' src='index.js'></script> 
</body> 
</html> 

common.css你的CSS :

body{ 
    margin:0; 
} 
#main{ 
    width:980px; margin:0 auto; 
} 

您對index.css CSS:

#button1,#button2{ 
    height:30px; width:300px; 
} 

注:

你可以使用一個CSS class,而不是逗號分隔id秒。這只是爲了告訴你語法應該是什麼樣子。您應該知道onclick在提交表單前觸發,因此重定向會在提交之前發生,因此使用submit按鈕沒有意義。除非你能解釋原因,否則在你的案例中填寫表格確實毫無意義。我只會用<a href='page1.php'>page 1</a>之類的東西,所以你甚至不需要使用JavaScript。您可以使用CSS將鏈接設置爲按鈕。

+0

我會在哪寫這篇文章? – user1904273