如何比较两个函数中定义的两个javascript变量值

时间:2013-10-15 11:49:36

标签: javascript jquery html

我有两个类似下面的javascript函数,它们将计算textareas中的非空白行。

HTML:

<div id="map-devlist" >
    <div class="block-with-text-area">
    <div class="input-quest-with-text-area">Enter your device list(one device in one line)</div>
    <div class="input-resp-with-text-area"><span><textarea  class="textarea" id="devs" name="devs" type="text" onkeyup="devscount();"></textarea></span> </div> 
    </div>
</div>

<div id="lunidlist" >
    <div class="block-with-text-area">
        <div class="input-quest-with-text-area">Enter your LUN IDs in Hex(one ID in one line)</div>
        <div class="input-resp-with-text-area"><span><textarea  class="textarea" id="lunids" name="lunids" type="text" onkeyup="luncount();"></textarea></span> </div>  
    </div>
</div>

<div id="error1"></div>

使用Javascript:

function devscount()
{
    devcounts = 0;
    var lines = $("#devs").val().split("\n");
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) devcounts++;
    }
}   

function luncount()
{
    luncounts = 0;
    var lines = $("#lunids").val().split("\n");
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) luncounts++;
    }

    if(devcounts == luncounts) {
        var message ="both counts are matching";
    } else {
        var message ="Mismatch between values";
        document.getElementById('error1').innerHTML=message;
    }
}

现在我想比较这两个textareas的行数,如果它们相等且不相等,我需要显示一条消息。但上面的脚本不适合我。当我在其相应的函数上回显document.getElementById('error1').innerHTML=devscount;document.getElementById('error1').innerHTML=luncounts;时,它会完美地显示行计数。但我无法比较他们的价值观。怎么做?

JSFIDDLE SETUP

2 个答案:

答案 0 :(得分:2)

你的jsfiddle的问题不仅仅是问题。您尝试检查值的方式也存在问题。 2个文本区域正在运行函数来计算密钥中的项目,但不运行比较代码。我更改了它们以运行第3个函数checkcounts,并将脚本修改为此...

var devcounts;
var luncounts;

function devscount() {
    devcounts = 0;
    var lines = $("#devs").val().split("\n");
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) devcounts++;
    }
}   

function luncount() {
    luncounts = 0;
    var lines = $("#lunids").val().split("\n");
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) luncounts++;
    }
}

function checkcounts() {
    devscount();
    luncount();

    var message;

    if(devcounts == luncounts) {
        message ="both counts are matching";
    } else {
        message ="Mismatch between values";
    }

    document.getElementById('error1').innerHTML=message;
}

<强> Working jsfiddle...

答案 1 :(得分:2)

让我觉得你写了很多代码来做一些非常简单的事情。我已在this fiddle中替换了您的代码。单一功能

function testCounts()
{
 var devCounts = $('#devs').val().split('\n').length;
 var lunCounts = $('#lunids').val().split('\n').length;
 var equals = (devCounts == lunCounts)?'Equal':'Not Equal';
 $('#error1').text(equals);
}

或者我完全错了。