2016-12-15 78 views
-2

我是一個初學者學習jQuery和web開發,所以這可能是一個愚蠢的問題,但我無法在Google上找到答案(可能我沒有搜索爲正確的關鍵字)。我有一個簡單的HTML文件(例如,'test.html',它載入jQuery,我寫的一個外部JavaScript文件(例如'test.js'),並且有一個按鈕。例如,當單獨的文件中包含jQuery點擊不起作用

<html> 
<head> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
<script src="scripts/test.js" type="text/javascript"></script> 
</head> 
    <body> 
    <ul class="nav nav-tabs"> 
       <li role="presentation"><a href="" id="summary_employee">Search by Name</a></li> 
       </ul> 
    </body> 
    </html> 

的Javascript

$(document).ready(function() { 
    $('#summary_employee').click(function (event) { 
     dataString = $("#summary_employee").serialize(); 
     $.ajax({ 
      type:"POST", 
      url:"<?php echo base_url(); ?>hodm_summary/search_by_employee", 
      data:dataString, 

      success:function (data) { 
       $('#search').html(data); 
      } 

     }); 
     event.preventDefault(); 
    }); 
}); 

但是當我按一下按鈕,這是行不通的。但是,當我把什麼「test.js」在「的test.html」代碼當時它的工作。

請幫我找到解決方案

+0

在'body'關閉之前放''script src =「scripts/test.js」type =「text/javascript」> – Mairaj

+0

您是否點擊了控制檯? –

+1

你把正確的文件?控制檯中的任何錯誤? –

回答

0

Becau在HTML標記加載到DOM之前,點擊的結果是綁定的。請將您的測試js文件放在dom加載後,然後點擊正確綁定。

<html> 
<head> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 

</head> 
    <body> 
    <ul class="nav nav-tabs"> 
       <li role="presentation"><a href="" id="summary_employee">Search by Name</a></li> 
       </ul> 
     <script src="scripts/test.js" type="text/javascript"></script> 
    </body> 
    </html> 

或者使用事件代表團

$(document).on('click', '#summary_employee', function (event) { 
    event.preventDefault(); 
    //Paste your code 
}); 
+0

這是行不通的 – xr33dx

+0

我試過活動委託,只刷新頁面 – xr33dx

+0

不行不行 – xr33dx

0

在test.js試試這個代碼

function getBaseUrl() { 
    pathArray = location.href.split('/'); 
    protocol = pathArray[0]; 
    host = pathArray[2]; 
    return protocol + '//' + host; 
} 

$(document).ready(function() { 
    $('#summary_employee').click(function (event) { 
     dataString = $("#summary_employee").serialize(); 
     $.ajax({ 
      type:"POST", 
      url: getBaseUrl() + "/hodm_summary/search_by_employee", 
      data:dataString, 

      success:function (data) { 
       $('#search').html(data); 
      } 

     }); 
     event.preventDefault(); 
    }); 
}); 

在test.js文件不能使用<?php echo base_url(); ?>,因爲它是一個PHP腳本。