使用Javascript修改HTML内容

发布于 2024-11-06 06:36:53 字数 210 浏览 3 评论 0原文

值得怀疑的是,这需要很多解释,但我想我需要第二双眼睛来检查这一点,因为我只是无法理解为什么它不会!尝试使用“能量计算器”,提交时不会返回任何值,尽管我以与有效的“电池电量计算器”相同的方式处理它。

关联: http://jsfiddle.net/Deva/426Jj/

Doubtful this needs much explaining but I think I need a second set of eyes to check this out because I just cannot fathom why it won't! Try using the "Energy Calculator" and no value will be returned when submitted despite me approaching it in the same way as the "Battery Charge Calculator" which does work.

Link:
http://jsfiddle.net/Deva/426Jj/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

岁月蹉跎了容颜 2024-11-13 06:36:53

为了详细说明 @alex 的答案,您选择了 jsFiddle 的 onLoad 选项,它将您的 JavaScript 代码放置在匿名函数中:

window.onload = function() {
    function energyCalc() {
        var mass = document.forms['0'].mass.value;
        var finalMass = mass * 1000;
        var velocity = document.forms['0'].velocity.value;
        var finalVelocity = velocity * 0.3048;
        var energy = (0.5 * (finalMass * (finalVelocity * finalVelocity)));
        if ((mass && velocity) != '') {
            document.getElementById("energy").innerHTML = 'Energy of weapon: ' + energy + ' Joules';
        } else {
            document.getElementById("energy").innerHTML = 'You must enter values in both fields!';
        }
    }
}

尝试一下大小:http://jsfiddle.net/mattball/Cbsa8/。我所做的就是选择无换行(头)无库

请记住,编写不引人注目的 JavaScript 是更好的编码习惯。在这种情况下,您可以使用 attachEvent 将事件处理程序与 JavaScript 绑定(对于 IE <9)或 addEventListener(对于真正的浏览器)。


编辑回复:OP编辑

打开控制台,在尝试使用能量计算器后问题立即显而易见:

> Uncaught TypeError: Cannot read property 'value' of undefined (fiddle.jshell.net:100)

就是这一行:

var mass = document.forms['0'].mass.value;

您访问了错误的表单。您需要将能量计算器代码中的所有 forms['0'] 更改为 forms[1]。请注意省略的引号,顺便说一句 - document.forms 是一个数组,而不是一个对象!

另外,您显然正在使用 jQuery,但您并没有在任何可以使用的地方使用它。为什么不呢?您的代码还有很大的改进空间。清理时间到了!

HTML

<div id="main">
    <a href="#"><h3>Battery Charge Calculator</h3></a>
    <div class="slide">
        <form id="batteryForm" action="">
            <p>
                Battery Capacity (mah):
            </p>
            <p>
                <input name="capacity"/>
            </p>
            <p>
                Charge Rate (mA):
            </p>
            <p>
                <input name="rate"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="time"/>
        </form>
    </div>
    <a href="#"><h3>Energy Calculator</h3></a>
    <div class="slide">
        <form id="energyForm" action="">
            <p>
                Mass of BB (grammes):
            </p>
            <p>
                <input name="mass"/>
            </p>
            <p>
                Power of weapon (FPS):
            </p>
            <p>
                <input name="velocity"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="energy"/>
        </form>
    </div>
</div>

JavaScript

$(function() {
    $('#main > a > h3').click(function() {
        $(this).closest('a').next('div.slide').animate({
            height: 'toggle'
        }, 750);
    });

    function batteryCalc() {
        var capacity = this.capacity.value,
            rate = this.rate.value,
            time = capacity / (rate / 1.2),
            chargeTime = (Math.round(10 * time) / 10).toFixed(1),
            message = 'You must enter values in both fields!';

        if (capacity && rate) {
            message = 'Required time on charge: ' + chargeTime + ' hours';
        }

        $('#time').html(message);
        return false;
    }

    function energyCalc() {
        var mass = this.mass.value,
            finalMass = mass * 1000,
            velocity = this.velocity.value,
            finalVelocity = velocity * 0.3048,
            energy = (0.5 * (finalMass * (finalVelocity * finalVelocity))).toFixed(1),
            message = 'You must enter values in both fields!';

        if (mass && velocity) {
            message = 'Energy of weapon: ' + energy + ' Joules';
        }

        $('#energy').html(message);
        return false;
    }


    $('#batteryForm').submit(batteryCalc);
    $('#energyForm').submit(energyCalc);
});

演示:http://jsfiddle.net/mattball/JSpaU/

To elaborate on @alex's answer, you have selected the onLoad option of jsFiddle, which places your JavaScript code inside of an anonymous function:

window.onload = function() {
    function energyCalc() {
        var mass = document.forms['0'].mass.value;
        var finalMass = mass * 1000;
        var velocity = document.forms['0'].velocity.value;
        var finalVelocity = velocity * 0.3048;
        var energy = (0.5 * (finalMass * (finalVelocity * finalVelocity)));
        if ((mass && velocity) != '') {
            document.getElementById("energy").innerHTML = 'Energy of weapon: ' + energy + ' Joules';
        } else {
            document.getElementById("energy").innerHTML = 'You must enter values in both fields!';
        }
    }
}

Try this on for size: http://jsfiddle.net/mattball/Cbsa8/. All I did was select no wrap (head) and No library.

Keep in mind that it's better coding practice to write unobtrusive JavaScript. In this case you'd bind the event handler with JavaScript, using attachEvent (for IE <9) or addEventListener (for real browsers).


Edit re: OP edits

Open a console and the problem is immediately obvious after trying to use the Energy Calculator:

> Uncaught TypeError: Cannot read property 'value' of undefined (fiddle.jshell.net:100)

which is this line:

var mass = document.forms['0'].mass.value;

You're accessing the wrong form. You need to change all cases of forms['0'] to forms[1] in the energy calculator's code. Note the omitted quotes, by the way - document.forms is an array, not an object!

Also, you're clearly using jQuery, but you're not using it everywhere you could. Why not? There's a lot of room for improvement in your code. It's cleanup time!

HTML

<div id="main">
    <a href="#"><h3>Battery Charge Calculator</h3></a>
    <div class="slide">
        <form id="batteryForm" action="">
            <p>
                Battery Capacity (mah):
            </p>
            <p>
                <input name="capacity"/>
            </p>
            <p>
                Charge Rate (mA):
            </p>
            <p>
                <input name="rate"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="time"/>
        </form>
    </div>
    <a href="#"><h3>Energy Calculator</h3></a>
    <div class="slide">
        <form id="energyForm" action="">
            <p>
                Mass of BB (grammes):
            </p>
            <p>
                <input name="mass"/>
            </p>
            <p>
                Power of weapon (FPS):
            </p>
            <p>
                <input name="velocity"/>
            </p>
            <p>
                <input type="submit" value="Submit"/>
            </p>
            <br/>
            <p id="energy"/>
        </form>
    </div>
</div>

JavaScript

$(function() {
    $('#main > a > h3').click(function() {
        $(this).closest('a').next('div.slide').animate({
            height: 'toggle'
        }, 750);
    });

    function batteryCalc() {
        var capacity = this.capacity.value,
            rate = this.rate.value,
            time = capacity / (rate / 1.2),
            chargeTime = (Math.round(10 * time) / 10).toFixed(1),
            message = 'You must enter values in both fields!';

        if (capacity && rate) {
            message = 'Required time on charge: ' + chargeTime + ' hours';
        }

        $('#time').html(message);
        return false;
    }

    function energyCalc() {
        var mass = this.mass.value,
            finalMass = mass * 1000,
            velocity = this.velocity.value,
            finalVelocity = velocity * 0.3048,
            energy = (0.5 * (finalMass * (finalVelocity * finalVelocity))).toFixed(1),
            message = 'You must enter values in both fields!';

        if (mass && velocity) {
            message = 'Energy of weapon: ' + energy + ' Joules';
        }

        $('#energy').html(message);
        return false;
    }


    $('#batteryForm').submit(batteryCalc);
    $('#energyForm').submit(energyCalc);
});

Demo: http://jsfiddle.net/mattball/JSpaU/

奈何桥上唱咆哮 2024-11-13 06:36:53

看到左边写着“onLoad”的下拉列表了吗?将其更改为“无包装(头)”即可工作。

See the drop-down list on the left that says "onLoad"? Change it to "no wrap (head)" and it'll work.

稀香 2024-11-13 06:36:53

这是因为 jsfiddle 的工作方式。您需要像这样声明 energyCalc 函数:

window.energyCalc = function() { ... }

It's because of the way jsfiddle works. You need to declare the energyCalc function like so:

window.energyCalc = function() { ... }
万人眼中万个我 2024-11-13 06:36:53

energyCalc() 包装在函数(load 事件的函数)中,并且对全局范围不可见。

Example

当它成为全局时它才起作用。

jsFiddle

energyCalc() is wrapped in a function (load event's function), and is not visible to the global scope.

Example

It works when it is made global.

jsFiddle.

相思碎 2024-11-13 06:36:53

删除 action = "javascript:energyCalc()"

并添加:

jQuery(document).ready(function()
{
    jQuery(document.forms[0]).submit(energyCalc);
});


没有 jquery

<form method="post" onsubmit="energyCalc();" >

编辑

还需要返回值(true 或 false)

查看:http://jsfiddle.net/SabAH/7/ http://jsfiddle.net/SabAH/11/

更新 解释

action 属性告诉浏览器要发布到哪里。该函数需要运行onsubmit

更新2查看新的jsfiddle

http://jsfiddle.net/426Jj/2/

有一些错误。首先,您的 action="javascript:..." 需要为 onsubmit="javascript: return ..." 并删除 energy 方法所需的提交按钮的 onclick引用 forms[1] 而不是 forms[0] 因为它是第二种形式。主要就是这样。

看看: http://jsfiddle.net/426Jj/2/

Remove the action = "javascript:energyCalc()"

and add:

jQuery(document).ready(function()
{
    jQuery(document.forms[0]).submit(energyCalc);
});


No jquery

<form method="post" onsubmit="energyCalc();" >

EDIT

Also need return values (true or false)

Check out: http://jsfiddle.net/SabAH/7/ http://jsfiddle.net/SabAH/11/

UPDATE an explanation:

The action attribute tells the browser where to post to. The function needs to be run onsubmit.

UPDATE2 After looking at the new jsfiddle

http://jsfiddle.net/426Jj/2/

There were a few errors. Firstly your action="javascript:..." needs to be onsubmit="javascript: return ..." and remove the onclick of the submit buttons the energy method needed to reference forms[1] not forms[0] becasue it was the second form. Thats mainly it.

look at: http://jsfiddle.net/426Jj/2/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文