Javascript 单击一次即可访问列表项的元素
大家好,我对jquery和css非常陌生,我正在尝试访问以下内容: 我试图在onClick函数“checkforappoint”中检查4个span标记内的值 html: 此时j和k都未定义 编辑: lolka_bolka建议的功能:Javascript 单击一次即可访问列表项的元素,javascript,jquery,html,css,Javascript,Jquery,Html,Css,大家好,我对jquery和css非常陌生,我正在尝试访问以下内容: 我试图在onClick函数“checkforappoint”中检查4个span标记内的值 html: 此时j和k都未定义 编辑: lolka_bolka建议的功能: function checkForAppointment(){ var AptBool=false; $('.something').click(function() { console.log('we have entered
function checkForAppointment(){
var AptBool=false;
$('.something').click(function() {
console.log('we have entered the .click function');
//Get all the span inside of it
var collection = $(this).find('span');
//Loop through all span object
$.each(collection, function(idx, obj) {
if ($(obj).html() > 0){
AptBool=true;
//return;
}
//Write the html value of span to the console.
//console.log('value here is ' + $(obj).html());
});
if (!AptBool){
alert('There is no appointment to view');
return;
}
});
//console.log('getting to the function anyway');
//var j = $('ul li').eq(0).text();
//var k = $('ul li').eq(1).text();
//console.log('j is ' + j + ' and k is '+ k);
};
因为您没有向我们提供HTML代码,而是证明了一个图像,我只举了一个小例子,希望您理解它的逻辑: HTML
<li class="something">
Click here
<div>
<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</li>
这应该是xml还是html<代码>http://54.72.173.92/console.png请在问题中而不是图片上显示您的html。jQuery中的所有方法都返回一个jQuery对象,它是DOM集合的包装器对象。。因此,当您调用.eq(0)时,将返回一个表示元素集合的jQuery对象。要获取该值,可以调用.eq(0).val()@Brewal,它是html。这是chrome控制台AAAA的屏幕截图,让它更容易理解。我在你的函数中添加了一点,当我点击一个列表项时,我似乎多次进入该函数。我不明白为什么?我将编辑我的原始问题以向您显示代码我将检查它。等一会儿,好的。删除
$('.something')。单击(function(){
行及其)}
结束标记。当我这样做时,我每次都进入'if'。检查这个:jsfiddle.net/9o5ylvvvvy/
function checkForAppointment(){
var AptBool=false;
$('.something').click(function() {
console.log('we have entered the .click function');
//Get all the span inside of it
var collection = $(this).find('span');
//Loop through all span object
$.each(collection, function(idx, obj) {
if ($(obj).html() > 0){
AptBool=true;
//return;
}
//Write the html value of span to the console.
//console.log('value here is ' + $(obj).html());
});
if (!AptBool){
alert('There is no appointment to view');
return;
}
});
//console.log('getting to the function anyway');
//var j = $('ul li').eq(0).text();
//var k = $('ul li').eq(1).text();
//console.log('j is ' + j + ' and k is '+ k);
};
<li class="something">
Click here
<div>
<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
</div>
</li>
$(function() {
//On li click where li has .something class
$('.something').click(function() {
//Get all the span inside of it
var collection = $(this).find('span');
//Loop through all span object
$.each(collection, function(idx, obj) {
//Write the html value of span to the console.
console.log($(obj).html());
});
});
});