2016-06-10 95 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

谢谢,这是做到了。 –