我有两个按钮,用于在单击时激活我的JavaScript函数,但它们似乎不起作用。但是,当我将JavaScript函数内容移到函数之外时,它们可以正常工作。所以按钮肯定是问题所在。
JavaScript的:
$(document).ready(function()
{
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney()
{
localStorage.clear()
}
});
HTML:
<p><button name="record" type="button" onclick="recordjourney()">Record Journey</button</p>
<p><button name="reset" type="button" onclick="resetjourney()">Reset Journey</button></p>
答案 0 :(得分:2)
按钮不是问题,因为您调用的函数与按钮不在同一级别,因此存在范围问题。
您可以通过绑定到就绪调用中的按钮来解决这个问题并使代码更清晰,如此
$(document).ready(function() {
$('[name="record"]').click(recordjourney);
$('[name="reset"]').click(resetjourney);
});
function recordjourney() {
var journey = JSON.parse(localStorage.getItem('journey')) || [];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
function resetjourney() {
localStorage.clear()
}
<p><button name="record" type="button">Record Journey</button</p>
<p><button name="reset" type="button">Reset Journey</button></p>
答案 1 :(得分:0)
将您的功能初始化为$(document).ready()
。
$(document).ready(function()
{
});
function resetjourney()
{
localStorage.clear()
}
function recordjourney()
{
var journey = JSON.parse(localStorage.getItem('journey'))||[];
journey.push(location.protocol + '//' + location.host + location.pathname);
localStorage.setItem('journey', JSON.stringify(journey));
document.write(journey);
}
答案 2 :(得分:0)
var recordjourney;
$(document).ready(function(){
...
recordjourney = {
var journey =
... etc
虽然,当然,鉴于你正在使用JQuery我会做
$(document).ready(function(){
...
$( 'button[name=record]' ).bind( function(){
//put your function here
})
并从按钮标签中删除丑陋的onclick =“recordjourney。