Jquery的新手。
我正在尝试使用jquery通过创建循环为每个“section”标签创建唯一的id。出于某种原因,下面的代码不起作用,我非常困惑,所以如果你有什么想法我做错了,请告诉我。
另外,我正在尝试将我的h2标签放在我的li标签内,然后在我的ul标签内部获取我的li标签。任何帮助也会受到赞赏。所有这些信息都应该在我的h1标签之后添加。
谢谢
$(document).ready(function() {
var h2 = $("h2");
$(h2).each(function(index) {
for (var index = 0; index < 4; index++) {
$(h2).attr("id", "section" + index);
$(h2).attr("href", "#");
}
});
var ul = $("<ul></ul>").find("ul");
var list = $("<li></li>").find("li");
$(".content h1").append(h2);
});
HTML ADDITION
<body>
<div class="concha">
<h1>The love of my life and how we met </h1>
<h3>The following is information on the Best thing that's ever happened to me</h3>
<h2>We met at the Park</h2>
<p>filler text</p>
<p>filler text</p>
<h2>We went to the movies</h2>
<p>filler text</p>
<p>filler text</p>
<h2>We had ice cream together</h2>
<p>filler text</p>
<p>filler text</p>
<h2>The end</h2>
<p>filler text</p>
<p>filler text</p>
答案 0 :(得分:3)
您正在循环遍历h2
元素两次。此外,您正在编写循环中的所有h2
元素。您需要在循环中使用this
来调用当前元素:
$(document).ready(function() {
var h2 = $("h2");
var i = 0; // define variable i as your "index"
$(h2).each(function(index) {
i++; // Increase i by 1 each time you loop through your h2 elements
$(this).attr("id", "section" + i); // Use $(this) to pull out the current element
$(this).attr("href", "#"); // Again, use $(this)
});
});
答案 1 :(得分:0)
这是我发现的一个很好的解决方案:
这是我的GetPasswordFromDB函数(我正在使用Mongo):
window.GetPasswordFromDB = function(ele)
{
var $row = $(ele).closest("tr");
// collects each field's content for that row.
user_name = $row.find("td:nth-child(1)").text();
target = $row.find("td:nth-child(2)").text();
system_type = $row.find("td:nth-child(3)").text();
window.GetIDFromDB(ele, user_name, target, system_type);
alert(ele.id);
$.ajax(
{
type: 'POST',
url: '/api/passwords/getPassword',
dataType: "text",
contentType: 'application/json',
async: true,
data: JSON.stringify({
user_name: user_name,
target: target,
system_type: system_type
}),
success: function(data)
{
console.log("Retrieved Password Successfully.");
window.ShowPassword(ele, data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("Deletion Failed");
}
});
}
要分配唯一的ID,我从数据库中获取一个objectID,然后在检索到该元素后将传递的元素ID分配给它:
window.GetIDFromDB = function(ele, ser_name, target, system_type)
{
$.ajax(
{
type: 'POST',
url: '/api/passwords/getID',
dataType: "text",
contentType: 'application/json',
async: true,
data: JSON.stringify({
user_name: user_name,
target: target,
system_type: system_type
}),
success: function(data)
{
console.log("Retrieved _ID Successfully.");
var dataSub = data.substring(1, data.length-1);
ele.id = dataSub;
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("ID Retrieval Failed");
}
});
}
我知道这与您要求的有所不同,但是如果这可以帮助任何人搜索此问题,请随时竖起大拇指!