0

我正在寻找定义一个变量:

var alumniName = // id from a list ( example: <li id="JoeJohnson">Joe Johnson</li> ).

我希望变量与访问者点击的内容相匹配。(例子:

<li id="JoeJohnson">Joe Johnson</li>  
// when a visitor clicks on the name Joe Johnson... the variable = JoeJohnson

<li id="FredSmith">Fred Smith</li>
// when a visitor clicks on the name Fred Smith... the variable = FredSmith

ETC... )

非常感谢任何帮助-谢谢-

4

3 回答 3

2

我们不得不对您的设置做出一些假设......但是在这里采取一个高峰,看看这是否有意义。不需要图书馆。

HTML

<ul id="myList">
<li data-name='Joe Johnson'>Joe Johnson</li>
<li data-name='Fred Smith'>Fred Smith</li>
</ul>

Javascript

var list = document.getElementById('myList'),
    alumniName;

Array.prototype.forEach.call(list.getElementsByTagName('li'), function(item) {
    item.onclick = function() {
        alumniName = this.getAttribute('data-name');
        // or if you feel you still want to use ID's to store the values (spaces are not allowed) you can just ref this.id
    };
});
于 2012-05-23T18:56:47.540 回答
1

您只能在点击发生时将变量设置为与点击相关的内容。使用事件监听器

var recentClickedId = null; // init, nothing clicked on now
// let this happen onload, i.e. when the DOM is available:
document.body.addEventListener("click", function(event){
    var el = event.target;
    if (el.nodeName.toLowerCase() == "li")
         recentClickedId = el.getAttribute("id");
}, false);
于 2012-05-23T18:56:37.670 回答
0

试试这个 HTML:

<ul>
<li data-name='Joe Johnson'>Joe Johnson</li>
<li data-name='Fred Smith'>Fred Smith</li>
</ul>

JavaScript(在身体负载时调用):

var alumniName = '';
var liElems = document.getElementsByTagName('li');

for (var i=0; i<liElems.length; i++)
{
    liElems[i].onclick = function(){  
        alumniName = this.getAttribute('data-name');
        alert(alumniName);
    };

}
于 2012-05-23T18:53:55.823 回答