我试图找到span的值。当我点击锚时它应该给我内部值。它应该是动态的。这是html
<div class="member-info">
<h2>Total Votes : <span>1</span></h2>
<a href="3" class="btn-system btn-medium border-btn vote_btn" data-target="#danger" data-toggle="modal">Vote</a>
</div>
这是jquery代码
$('.vote_btn').on('click',function(){
var id = $(this).attr('href');
var method_url = "<?php echo base_url(); ?>Home/vote/"+ id;
$.ajax
({
type: "POST",
url : method_url,
success:function(data)
{
if(data=='1')
{
var votes = $(this).siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Thanks you and come back tomorrow to vote again.');
}else if(data=='0')
{
var votes = $(this).siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Sorry you have already voted today, please come back tomorrow to vote again.');
}
$('#response_modal').modal('show')
}
});
});
这段代码给了我未定义的值,而我希望在点击锚点投票时获得span元素中的值。请帮忙
答案 0 :(得分:2)
您无法直接在成功函数中访问$(this),分配变量并在成功函数中访问它
$('.vote_btn').on('click',function(){
var id = $(this).attr('href');
var method_url = "<?php echo base_url(); ?>Home/vote/"+ id;
var $current_element = $(this);
$.ajax
({
type: "POST",
url : method_url,
success:function(data)
{
if(data=='1')
{
var votes = $current_element.siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Thanks you and come back tomorrow to vote again.');
}else if(data=='0')
{
var votes = $current_element.siblings('h2').children('span').text() ; alert(votes);
$("#vote_response").html('Sorry you have already voted today, please come back tomorrow to vote again.');
}
$('#response_modal').modal('show')
}
});
});
答案 1 :(得分:1)
使用.text()
代替.val()
。 .val()
函数用于查找输入的值,而span元素不是输入。 .text()
函数将在范围内找到文本。
$('.vote_btn').on('click',function(){
var votes = $(this).siblings('h2').children('span').text() ; alert(votes);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="member-info">
<h2>Total Votes : <span>1</span></h2>
<a href="3" class="btn-system btn-medium border-btn vote_btn" data-target="#danger" data-toggle="modal">Vote</a>
</div>
答案 2 :(得分:0)
使用.text()或.html()代替.val(),因为span没有值属性