我有一个循环,它从数据库中检索值并将其放入无序列表中。我想要做的是在同一个列表元素中检索标题的值。
说这是我的意思,我想得到"这是一个标题"当我点击第一个链接并获得"这是第二个标题"单击第二个链接时依此类推。我尝试使用$(this).parent().text()
,但它返回" undefined" ...
<ul>
<li>
<h3 class="title">This is a title number two</h3>
<a href="#">Delete</a>
<li>
<li>
<h3 class="title">This is a title</h3>
<a href="#">Delete</a>
<li>
</ul>
这是完整的脚本:
<?php
require_once('db.php');
$sql = "SELECT id, name, user, done, created FROM todos";
$result = mysqli_query($conn, $sql);
$id = $_GET['id'];
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Todo App</title>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript">
function checkDelete(event){
var item_name = $('#title').text();
var answer = confirm("Delete " + item_name + "?");
if(!answer){
event.preventDefault();
return false;
}
}
</script>
</head>
<body>
<div class="items">
<h2>Your todo list</h2>
<ul>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>' . '<p id="title">' . $row['name']. '</p>' .'<a href=delete.php?id='. $row['id'] .' onClick=checkDelete(event)>Delete</a>';
echo '<a class="update" href=todo.php?id='.$row['id'].'&name=' . urlencode($row['name']) .'>Update</a></li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</ul>
</div>
<form id="todo" action="addtodo.php" method="post">
<label for="item">Add</label>
<input type="text" name="item" id="item">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
&#13;
答案 0 :(得分:2)
使用
$(this).parent().text()
赢了,因为$(this).parent()
将选择<li>
元素,而.text()
没有任何值设置
选择一个标签并设置一个on click事件监听器并获取前一个元素的值
$('a').on('click', function() {
var title = $(this).prev().text();
});
答案 1 :(得分:1)
$(document).ready(function(){
$('.title').on('click',function(){
alert($(this).siblings('h3').html());
})
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li>
<h3>This is a title number two</h3>
<a class="title" href="#">Delete</a>
<li>
<li>
<h3>This is a title</h3>
<a class="title" href="#">Delete</a>
<li>
</ul>
&#13;