0

示例基于此答案https://stackoverflow.com/a/7132830/2465936

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

如果点击<p id ="2310">click here to set variable to 2310</p>

然后在<div id="load"></div>显示2310

或者myVariable=targ.id;变成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=targ.id;值是点击文本。

据了解需要这样的东西

``var myVariable = $("#???clicked id????").text();`

但是不明白如何在代码中正确实现

请指教

4

1 回答 1

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;
}

演示:http: //jsfiddle.net/aGWGn/5/

注意:如果我没记错的话,在 HTML5 中 anid可以是你想要的,但在 HTML5 之前它应该以字母开头,而不是数字。

于 2013-07-12T19:50:25.073 回答