1

在我的脚本中,我有一个函数createEl(),我在其中声明 2 个变量并调用 2 个其他函数,将这些声明的变量传递给这 2 个函数。

通过单击一个链接,第一个功能应该将 10px 添加到divp's 高度。通过单击另一个链接,第二个函数应该从div的高度中减去 10px。

虽然它没有按预期工作。我相信我必须以某种不同的方式从我的第一个函数中调用这两个函数?现在的结果是,无论我点击哪个链接,那 10px 总是被扣除。请帮忙。

PS我正在寻找一个没有全局变量的选项,而只是将变量作为参数从一个函数传递给多个函数。

HTML:

<a href="" onclick="createEl();return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl();return false;">Smaller</a>

<div id='box'></div>

JavaScript:

function createEl() {
    var x = document.getElementById('box');
    var h = x.offsetHeight;

    large(x,h);
    small(x,h);
}

function large(x,h) {
    x.style.height = h + 10 + "px";
}

function small(x,h) {
    x.style.height = h - 10 + "px";
}
4

2 回答 2

3

更新您的 HTML 以将标识符参数发送到函数调用。

<a href="" onclick="createEl('large');return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="createEl('small');return false;">Smaller</a>
<div id='box'></div>

JavaScript:

function createEl(funcName){

        var x = document.getElementById('box');
        var h = x.offsetHeight;

        if(funcName =="large") large(x,h); //depending on the parameter call the required function
        else small(x,h);
}
于 2012-05-15T13:24:04.380 回答
2

您可以将偏移量作为参数传递,并创建一个通用changeHeight(offset)函数。

这符合您的要求吗?

HTML:

<a href="" onclick="changeHeight(10);return false;">Larger</a>&nbsp;&nbsp;
<a href="" onclick="changeHeight(-10);return false;">Smaller</a>
<div id='box'></div>

JavaScript:

changeHeight(offset) {
    var x = document.getElementById('box');
    x.style.height = (x.offsetHeight + offset) + "px";
}
于 2012-05-15T13:28:30.840 回答