$("#test").on('click', begin);
function begin(){
var test = ["apple","pear","banan"];
for (var i=0; i < test.length; i++){
console.log(test[i]);
var listItem = document.createElement('text'),
html = `<pstyle='margin-left:12%;padding- top:8%;color:white;font-family:testFont1;font-size:15px;'> ${test[i]} </p>
<pstyle='margin-left:3%;color:white;font-family:testFont1;font-size:17px;line-height:5px;'>${'someothertext'}</p>
<pstyle='margin-left:3%;color:white;font-family:testFont1;font-size:12px;line-height:10px;'>
${test[i]}</p>
<pstyle='margin-left:3%;padding-bottom:8%;color:white;font-family:testFont1;font-size:12px;line-height:-10px;'>${'someothertext'}</p>`;
listItem.innerHTML = html;
allresults.appendChild(listItem);
$(listItem).on('click', testAlert);
}
}
function testAlert(e){
let text = $(e.target.parentElement.firstChild).html().trim();
alert(text);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="searchResults">
<div id="allresults" >
</div>
</div>
<button id=test>click me</button>
我想点击一个名为div
的allresults
标签,div
标签应该在数据集中返回一个设定值。在我的情况下,它将是appleType
。
但是我不知道为什么我不能只输入名为div
的allresults
标签的任何部分。我必须非常具体地点击appleType
然后它会告诉我警报。如果我点击任何其他地方,它会提醒undefined
。
所以我想要的是能够在任何地方点击以获得appleType
的警报。
我的JS中的for循环循环遍历数据库并在div
标签中显示我的HTML页面中的所有值allresults
我的JS档案:
for(var i = 0; i < res.rows.length; i++){
var listItem = document.createElement('text'),
html = " res.rows.item(i).appleType + "<br>" + res.rows.item(i).pearType;
listItem.dataset.appleType = res.rows.item(i).appleType;
listItem.innerHTML = html;
allresults.appendChild(listItem);
}
我的Html文件:
<div id="searchResults" style="margin-top:40%" >
<div id="allresults" style="background-image:url(css/images/SidePanel/searchWidgetBG.png);background-size:100%;margin-top:1%">
</div>
</div>
我的JS文件调用tapped div:
function testAlert(e){
var appleType = e.target.dataset.appleType;
alert(appleType);
}
$('#allresults').on('click', testAlert);
好的源代码,我将编辑我的答案:
你的问题是你将所有的html集中到同一个实体中,并且你假设你可以为你正在创建的那个东西设置一个属性。如果您愿意,e或事件不会将该属性应用于它,因为它是事件本身的新实例。
试试这个:
$(e.target).get(0).firstChild.data;
或者一个非jquery路线做同样的事情:
e.target.firstChild.data
这将返回您单击的元素的第一个块,并忽略br标记和以下标记。我希望这就是你所需要的。