[英]javascript equivalent of jquery for this function
在動態生成的“ ol”中:
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
我需要找到單擊的“ li”,我僅將jquery庫用於此功能,我正在javascript中搜索相同的功能,但此刻我還不知道如何編碼。 thx var ss; SS = $( “#idfromOl”); ss.click(clickhecho);
}
function clickhecho()
{
var $all_lis = $('li');
$all_lis.on('click', function() {
var index = $all_lis.index(this);
});
}
嘗試這個:
function createfunc(i) {
return function() { alert(i); };
}
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML ="test"
newLi.appendChild(link);
// just add onclick event; use createFunc to create function closure (otherwise 'i' would always be the last 'i'
newLi.onclick = createfunc(i);
olnew[0].appendChild(newLi);
}
我可能會記錯了,但這是您要尋找的東西嗎?
var elements = document.getElementsByTagName('li');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function (e) {
$("#clickedLi").text(e.srcElement.id);
});
}
它將一個名為addEventListener
的事件附加到每個li
元素。
在每個li
元素內部,都有一個click
事件作為參數給出,其中包含被點擊li
的id
。
演示: http : //jsfiddle.net/DUzMc/1/
最簡單的方法是在生成列表時包括事件:
document.getElementsByTagName('ol');
for (i = 0; i < len; i++){
var newLi = document.createElement("li");
var link = document.createElement('a');
link.href = "#";
link.innerHTML = (results.rows.item(i).location + "-" + results.rows.item(i).datte);
// Add this
link.onclick = function(index) { return function() {
// do something with index variable
}}(i);
newLi.appendChild(link);
olnew[0].appendChild(newLi);
注意,我使用局部變量索引而不是i,這是因為單擊該項目時,i的值將不同(等於len)。
您的腳本的第一部分不完整,因此我做了一個簡短的腳本來生成動態列表。
基本上,您正在尋找addEventListener() :
var elements = 10;
ol = document.createElement('ol');
for(i = 1; i <= elements; i++){
var li = document.createElement('li');
var a = document.createElement('a');
a.setAttribute('href', '#');
a.text = 'Link ' + i;
li.appendChild(a);
ol.appendChild(li);
a.addEventListener("click", who, false); // THIS IS THE IMPORTANT PART
}
document.getElementsByTagName('body')[0].appendChild(ol);
function who(e){
var myTarget = e.target;
myTarget.text = "clicked!";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.