【问题标题】:How to delete parts of local storage with removeItem?如何使用 removeItem 删除部分本地存储?
【发布时间】:2014-01-05 19:25:18
【问题描述】:

我正在创建一个跟踪人们体重的网络应用程序。我有一个页面,其中一个数组存储在本地存储中并显示给用户。

我现在正在处理的页面,输入用户的目标体重并显示给他们。

我最初使用 localStorage.clear() 进行此操作,但我注意到这也擦除了我在另一页上的数组。我正在尝试使用 localStorage.RemoveItem,但它似乎只是删除了输入按钮而不是数据。

谁能帮我解决这个问题?

这是我的脚本。

更新*

function storeText(inputID) {

//Clears old target weight
//localStorage.clear(); 

//check to see if the localStorage item already exists
var userInput = localStorage.userInfo;

//set it up for new data to be appended
if(userInput!=null) userInput+=" ";
else userInput="";

//add the new data
userInput += document.getElementById(inputID).value;

//set the localStorage field with the updated data
localStorage.userInfo = userInput;




}

 function UpdateWeight(inputID){

    localStorage.userInfo = document.getElementById(inputID).value;

    document.getElementById("result").innerHTML = localStorage.userInfo;

}


</script>

输入

<input size="10" id="userText" type="text"/>            
        <input type="button" class="greyButton" value="submit" onclick= "UpdateWeight(inputID)"/>
        <div id="result">           
        Result here
        </div>

【问题讨论】:

    标签: javascript html local-storage


    【解决方案1】:

    重命名函数

    remove(); 
    

    removeStorage();
    

    记得更新 onClick。

    remove(); 
    

    在按钮上运行而不是调用你的函数!

    一个更简洁的功能是:

    function UpdateWeight(inputID){
    
        localStorage.userInfo = document.getElementById(inputID).value;
    
        document.getElementById("result").innerHTML = localStorage.userInfo;
    
    }
    

    从您所展示的内容来看,这是您想要的 - 在按钮单击时将原始项目替换为新项目?

    【讨论】:

    • 对不起,我没有看到你评论的下半部分,我会试试你的功能。
    • 按 wak - onclick 应该只包含一个函数 UpdateWeight - 其他的不是必需的。
    • 所以 UdateWeight 函数是我唯一需要的函数吗?它还没有打球
    • UpdateWeight(inputID) 必须是 UpdateWeight("userText") - 你必须传入你想要的 ID。
    • 我通过添加 localStorage.userInfo = document.getElementById(inputID).value;到我原来的商店文本功能的底部。干杯!!
    猜你喜欢
    • 2017-11-25
    • 1970-01-01
    • 2018-02-04
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2018-01-25
    • 1970-01-01
    相关资源
    最近更新 更多