单击文本并将文本设置/定义为javascript变量的值

时间:2013-07-12 19:41:09

标签: javascript

示例基于此答案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 = $(&#34;#??? clicked id ????&#34;)。text();`

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

请咨询

1 个答案:

答案 0 :(得分: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;
}

DEMO http://jsfiddle.net/aGWGn/5/

注意:如果我记得很清楚,在HTML5中id可以是您想要的,但在HTML5之前它应该以字母开头,而不是数字。