2016-06-10 24 views
1

我想要做的是從另一個文件(可以說是new_machine.php)加載一個輸入表單到我的index.php。在這種形式中,我有一個下拉式輸入,它從MySQL數據庫中獲取選項並將它們列爲錨。這工作正常。然後我想用jQuery的.click()方法來控制用戶的輸入,所以當點擊某個錨時,我將能夠得到它的文本並將其設置爲下拉按鈕的值。然而,這並沒有發生,因爲它似乎沒有觸發jQuery的動作。所以我的問題是如何在我的index.php中加載的.html/.php中使用jQuery。我的文件是這樣的:JavaScript/JQuery不能在裝入load的html中工作()

new_machine.php - 表單 - 我知道沒有輸入的下拉列表,我只想得到文本顯示在按鈕中,所以我知道jQuery的作品。

<div class="tab-content"> 

... some text inputs 

<label> 
    Purchase date<span class="req">*</span> 
</label> 
<input type="date" required="" /> 


<label> 
    Machine<span class="req">*</span> 
</label> 

    <div class="dropdown"> 
     <button id="chosenGroup" class="dropbtn">Choose machine</button> 
     <div class="dropdown-content" id="machineList" > 
      <?php 
       session_start(); 
       try { 
        $bdd = new PDO('mysql:host=******:****; dbname=track', '*****', '*****'); 
       } catch(Exception $e) { 
        exit('Unable to connect to db.'); 
       } 

       $sql = "SELECT * FROM machinegroup WHERE UserID=:uid"; 
       $q = $bdd->prepare($sql); 
       $q->bindParam(':uid', $_SESSION['valid_user']); 
       $q->execute(); 
       while ($row = $q->fetch(PDO::FETCH_ASSOC)) 
       { 
        echo "<a href=\"#\" class=\"machineGroupClick\">". $row['Name'] ."</a>"; 
       } 
      ?> 
     </div> 
    </div> 


<script>  
$(document).ready(function(){ 
    $('.machineGroupClick').click(function(){ 
     var name = $(this).html(); 
     $('#machine-content').text('lalal'); 
     $('#chosenGroup').html(name); 
    }); 
}); 
</script>   


</div> 

的index.php

<head> 
... 
<script src="https://code.jquery.com/jquery.js"></script> 
<script src="machines/js/data.js"></script> 
... 
</head> 

<body> 
... 
<a href="#" id="new-machine">...</a> 

... 

<div id="machine-content" class="col-md-9" style="float:right"> 

... 

</body> 

data.js(這是jQuery腳本來處理點擊等事件在我的index.php)

$('#new-machine').click(function(){ 
    $('#machine-content').load('new_machine.php'); 
}); 

我也試圖把index.php和data.js中來自new_machine.php的jQuery代碼,但它從來沒有工作過。所以我的問題是什麼是加載部分HTML/PHP時使用jQuery的正確方法?我錯過了關鍵的東西嗎?如果代碼全是index.php並且沒有加載,Dropdown就可以正常工作,但是當用戶點擊「New machine」時,我想讓它在頁面內部加載。乾杯

+0

用[對()](http://api.jquery.com/on/)方法來綁定事件 – madalinivascu

+0

對於動態生成的元素 – anu

回答

2

data.js應該是這樣的:

$(document).ready(function(){ 
    $('#machine-content').on('click','.machineGroupClick',function(){//use event delegation here because your html is in the partial and it is loaded after the dom ready 
     var name = $(this).html(); 
     $('#machine-content').text('lalal'); 
     $('#chosenGroup').html(name); 
    }); 
    $('#new-machine').click(function(){ 
    $('#machine-content').load('new_machine.php'); 
    }); 
}); 
在父的index.php
+0

謝謝,這是做到了。 –