2013-07-12 27 views
0

實施例的值是基於此答案https://stackoverflow.com/a/7132830/2465936點擊文本和集合/定義文本,如JavaScript變量

下面是工作示例http://jsfiddle.net/rigaconnect/aGWGn/3/

如果點擊<p id ="2310">click here to set variable to 2310</p>

然後在<div id="load"></div>顯示器2310

或​​變成點擊元素的id=

這裏是代碼

function whichElement(e) { 
var targ; 
if (!e) { 
var e=window.event; 
} 
if (e.target) { 
targ=e.target; 
} 
else if (e.srcElement) { 
targ=e.srcElement; 
} 
if (targ.nodeType==3) {// defeat Safari bug 
targ = targ.parentNode; 
} 
myVariable=targ.id; 
document.getElementById("load").innerHTML=myVariable; 
} 

<body id="-1" onmousedown="whichElement(event)"> 
<p id="3.14">click here to set variable to 3.14</p> 
<h3 id="5">click here to set variable to 5</h3> 
<p id ="2">click here to set variable to 2</p> 
<p id ="2310">click here to set variable to 2310</p> 
<div id="load"></div> 

需要獲取以下行爲:

如果點擊<p id ="2310">click here to set variable to 2310</p>

然後在<div id="load"></div>顯示click here to set variable to 2310

或​​值被單擊的文本。

由於瞭解需要像這樣

``變種MYVARIABLE = $( 「#???點擊ID ????」)文本();`

但不知道如何正確地執行它的代碼

請指點

回答

1

HTML:

<body id="-1"> 

<p id="3.14">click here to set variable to 3.14</p> 
<h3 id="5">click here to set variable to 5</h3> 
<p id ="2">click here to set variable to 2</p> 
<p id ="2310">click here to set variable to 2310</p> 

<div id="load"></div> 

JS:

document.body.onmousedown = whichElement; 
var output = document.getElementById("load") 
function whichElement(e) { 
    e = e || window.event; 
    var targ = e.target || e.srcElement; 
    if (targ.nodeType===3) {// defeat Safari bug 
     targ = targ.parentNode; 
    } 
    output.innerHTML = targ.innerHTML; 
} 

DEMOhttp://jsfiddle.net/aGWGn/5/

注:如果我記得很清楚,在HTML5的id可以是你想要的,但HTML5之前,它應該以一個字母,而不是數字開頭。