2013-11-26 111 views
-4

這裏是我的JS代碼JS功能不能正常工作

$(document).ready(function() { 

    **$('.sel1').hide();** 

    function show_names(str,val) { 
    alert("hello"); 
    $('.sel1').show(); 
    $.getJSON('j_process.php?j=1&str='+str+'&val='+val, function (data) { 
     var html = ''; 
     var len = data.length; 
     for (var i = 0; i< len; i++) { 
     html += '<option>' + data[i].name + '</option>'; 
     } 
     $('.sel1').append(html); 
    }); 
    return false; 
    } 
    return false; 
}); 

這裏是我的HTML:

<div class="control-group"> 
    <label for="textfield" class="control-label"><?php if($i==$num_row-1) { echo "Save File As"; } else { echo str_replace("_"," ",$row[0]); } ?></label> 
    <div class="controls"> 
    <input type="text" <?php if($main_box==$i) { echo 'onkeyup="show_names(this.value, '.$main_box.')"';} ?> id="textfield" name="loc<?php echo $i; ?>" <?php if($i==$num_row-1) { echo "autocomplete='off' onkeyup='searchfile(this.value);' "; }?> value="<?php if(isset($_SESSION['loc'.$i])) { echo $_SESSION['loc'.$i]; }?>" maxlength="500" size="50" class="input-xlarge"> 
    </div> 
</div> 

我把外面的讀取文件的功能,但的getJSON現在沒有工作。

+0

您正在使用什麼版本的jQuery的調用函數show_names? – krillgar

+7

這是一個函數定義,把它放在'$(document).ready(...)'位 – Tallmaris

+2

以外$ main_box的值是多少? – SHIN

回答

0

show_names()未在您發佈的代碼中的窗口範圍內定義。它只在document.onReady處理程序的範圍內定義,所以它不能由頁面的其餘部分調用。

+0

我怪我的flakey PHP解析器在我的代碼閱讀器中的最初錯誤... –

+0

警報框現在可以工作,但getJSON不起作用。 – Ankur

1

正如@Tallmaris所說,您需要將功能定義移到document.ready函數之外,否則您的頁面將無法看到它。

例子:

function foo(){ 
    function bar(){ 

    } 
    //I can call bar in here. 
    bar(); 
} 

function someOtherFunction(){ 
//But I can't call bar() here because it's nested within foo. 
} 
+0

警報框現在可用,但getJSON不起作用。 – Ankur

0

show_names範圍限定爲您document.ready處理程序。它不能從外部調用,因爲它沒有全局作用域。

$(document).ready(function() { 
    $('.sel1').hide(); 
}); 

function show_names(str,val) 
{ 
    alert("hello"); 
    $('.sel1').show(); 
    $.getJSON('j_process.php?j=1&str='+str+'&val='+val, function(data){ 
     var html = ''; 
     var len = data.length; 
     for (var i = 0; i< len; i++) { 
      html += '<option>' + data[i].name + '</option>'; 
     } 
     $('.sel1').append(html); 
    }); 
return false; 
} 

嘗試。應該適合你的工作。

+0

警報框現在可用,但getJSON不起作用。 – Ankur

+0

什麼是不工作?它運行嗎? –

0
$(document).ready(function() { 
    $('.sel1').hide(); 
    return false; 
}); 
function show_names(str,val) 
{ 
    alert("hello"); 
    $('.sel1').show(); 
    $.getJSON('j_process.php?j=1&str='+str+'&val='+val, function(data){ 
    var html = ''; 
    var len = data.length; 
    for (var i = 0; i< len; i++) { 
     html += '<option>' + data[i].name + '</option>'; 
    } 
     $('.sel1').append(html); 
    }); 
    return false; 
} 

並確保

+0

警報框現在可用,但getJSON不起作用。 – Ankur