[英]how to get value of li tag which is in ul tag using getElementById
[英]How to trim <ul> and <li> tag, but the value of <li> will be the remain same?
我創建了一個ajax方法來搜索用戶列表。 但是ajax函數返回我,例如:
<ul><li>User Name</li></ul>
我想修剪主頁中的<ul></ul>
和<li></li>
標簽以使用確切的值。
喜歡 :
之前:
<ul><li>User Name</li></ul>
之后:
用戶名
Ajax結果將存儲在:
<div class="input-group" id="userList"></div>
我已經做過一些javascript方法
< script >
$(document).ready(function() {
$('#run').keyup(function() {
var query = $(this).val();
if (query != '') {
$.ajax({
url: "userSearch.php",
type: "POST",
data: {
query: query
},
success: function(data) {
$('#userList').fadeIn();
$('#userList').html(data);
paymentStatus(data);
}
});
} else {
$('#userList').fadeOut();
}
});
$(document).on('click', 'li', function() {
$('#run').val($(this).text());
$('#userList').fadeOut();
});
}); <
/script>
<?php
require_once '../../config/config.php';
if(isset($_POST['query']))
{
$output = '';
$query = "SELECT Name, Id FROM ucoe_users WHERE Name LIKE '%".$_POST['query']."%' AND RoleId = 3";
$result = mysqli_query($connection, $query);
$output = '<ul>';
if(mysqli_num_rows($result)> 0 )
{
while($row = mysqli_fetch_array($result))
{
$output .= "<li>".$row['Name']."</li>";
}
}
else
{
$output .= '<li>User Not Found</li>';
}
$output .= "</ul>";
echo $output;
}
?>
使用$(html).text()
從HTML獲取文本值
success: function(data) {
$('#userList').fadeIn();
$('#userList').html($(data).text());
paymentStatus(data);
}
var html = '<ul><li>User Name</li></ul>'; console.log($(html).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
您可以按以下方式使用jQuery,
var arrOfValues = [];
$('ul li').each(function(i)
{
arrOfValues.push($(this).text()); //every value of ul li will be push in arrOfvalues.
});
$('#userList').fadeOut();
如果它是一個DOM元素,那么直接獲取innerText就可以了。
例如:
<ol>
<li>User Name</li>
</ol>
<script>
var olDom = document.getElementsByTagName("ol");
console.log(olDom[0].innerText)
</script>
但是在您的情況下,您將HTML作為Ajax的響應,因此首先我們需要創建一個包裝器div,以DOM形式保存您的響應,然后再調用innerText。
<script>
var wrapperDiv = document.createElement('div');
wrapperDiv.innerHTML = data;
$('#userList').html(wrapper.innerText);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.