gpt4 book ai didi

javascript - 使用本地存储和 JQuery 保存 null

转载 作者:行者123 更新时间:2023-11-30 21:10:00 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery 在页面上加载一个按钮,当有人单击该按钮时,我希望 onclick 函数发生并将 id 值保存在本地存储中。

然而,当我登录到控制台时,这给了我一个空值!这是错误的吗?我怎样才能做到这一点?

var str = '<div class="row">
<div class="col-md-4">
<div class="thumbnail">
<img src="' + poster + '"alt="Poster_here">
<div class="caption"><h3>' + title +'</h3><p>' + desc + '</p><p>
<a href="" class="btn btn-primary" role="button"
script="onclick()=function(){localStorage.setItem("idd","' +
id + '");' +'}">Read More and Explore</a> </p></div></div></div>
</div>';
$('#add_all_here').append(str);

HTML:-

<div class="container-fluid">
<div id="add_all_here">

</div>
</div>

最佳答案

您的代码按预期运行。
我想我知道是什么导致您认为它没有运行。
<a>里面的这一行标签:script="onclick()=function(){localStorage.setItem("idd","' + id + '")这不是附加事件处理程序的方法。

您需要将函数引用传递给具有事件名称的属性。
所以而不是 script=onclick...
应该是:onclick='functionName(event)'
另一件事是,您需要阻止重定向到网站,以便提供时间在本地存储中设置内容,然后才重定向客户端。
所以你可以使用 event.preventDefault()停止重定向,然后从 href 中获取 url属性并设置 window.location .

这是一个使用您修改后的代码的工作示例(我不能在片段中使用本地存储,所以我使用了 console.log ):

function setLocalStorage(e){
e.preventDefault();
var id = e.target.getAttribute('data-id');
var url = e.target.href;
console.log('saving id - ' + id);
console.log('redirecting to - ' + url);
//window.location = url; //this will redirect
}

var poster = 'sdsd',
title = 'blah',
desc= 'skjdksdj ksjd ',
id= 457

var str = '<div class="row"><div class="col-md-4"> <div class="thumbnail"> <img src="' + poster + '"alt="Poster_here"><div class="caption"><h3>' + title +'</h3><p>' + desc + '</p><p><a href="http://example.com" class="btn btn-primary" data-id="' + id + '" role="button" onclick="setLocalStorage(event)">Read More and Explore</a> </p></div></div></div></div>';
$('#add_all_here').append(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
<div id="add_all_here">

</div>
</div>

关于javascript - 使用本地存储和 JQuery 保存 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com