Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取上一个元素的id?_Javascript_Jquery - Fatal编程技术网

Javascript 如何获取上一个元素的id?

Javascript 如何获取上一个元素的id?,javascript,jquery,Javascript,Jquery,以下是html: <li> <a href="/someurl" id="4">some text</a> <i class="geta glyphicon glyphicon-remove-circle" onclick="deleteAnch();"></i> </li> <li> <a href="/otherurl" id="5">other text</

以下是html:

<li> 
    <a href="/someurl" id="4">some text</a>
    <i class="geta glyphicon glyphicon-remove-circle" onclick="deleteAnch();"></i>   
</li>

<li> 
  <a href="/otherurl" id="5">other text</a>
  <i class="geta glyphicon glyphicon-remove-circle" onclick="deleteAnch();"></i>

</li>
但在控制台里我得到了

id为:未定义

这里出了什么问题?如何解决


p、 我知道有人问了一些类似的问题,但我仍然无法使用其他答案来解决这个问题。

您需要将当前元素内容,即
传递给
删除anch
内联单击处理程序

<i class="geta glyphicon glyphicon-remove-circle" onclick="deleteAnch(this);"></i>

但是,在使用jQuery时,应该使用它绑定事件。传递
deleteAnch
的函数引用,并摆脱内联单击处理程序

function deleteAnch () {
    var the_id = $(this).prev('a').attr('id');
    console.log('The id is:', the_id);        
}

$('i.glyphicon-remove-circle').on('click', deleteAnch);
函数deleteAnch(){
var the_id=$(this).prev('a').attr('id');
log('id为:',id);
}
$('i.glyphicon-remove-circle')。在('click',deleteAnch')

  • 偶像
  • 偶像

您需要将当前元素内容,即
传递给
deleteAnch
内联单击处理程序

<i class="geta glyphicon glyphicon-remove-circle" onclick="deleteAnch(this);"></i>

但是,在使用jQuery时,应该使用它绑定事件。传递
deleteAnch
的函数引用,并摆脱内联单击处理程序

function deleteAnch () {
    var the_id = $(this).prev('a').attr('id');
    console.log('The id is:', the_id);        
}

$('i.glyphicon-remove-circle').on('click', deleteAnch);
函数deleteAnch(){
var the_id=$(this).prev('a').attr('id');
log('id为:',id);
}
$('i.glyphicon-remove-circle')。在('click',deleteAnch')

  • 偶像
  • 偶像