2016-09-08 14 views
1

昨日の夕方、データを出力し、自分のインデックスページの自分のフォームからコンテンツページに送信し、その結果を自分のコンテンツ内に表示するようにしました。ページ。データの出力時にスクリプトが正常に機能しない

しかし、今私は新しい問題があります。私のJavaScriptは、ビューポートを混乱させない限り、自分のコンテンツdivにその関数(renderGrid)を適用しません。なぜなら、window.addEventListener( "resize"、renderGrid、false);遊びに来る。

私はそれをどのように説明するのか分かりません。

おかげで、

index.htmlを

<form id="search_form" action="content.php" method="POST">   
    <input id="form_search" type="search" name="name">    
    <input id="form_submit" type="submit" name="submit" value="Enter"> 
</form> 

<div id="content"></div> 

JS

$(document).ready(function(){ 
    var form = $('#search_form'); 
    form.submit(function(event){ 
     var form_search = $('#form_search').val(); 
     if($.trim(form_search) != '') { 
      $.post("content.php", {name: form_search}, function(data){ 
       $('#content').html(data);  
      }); 
     } 
     event.preventDefault(); 
    }); 
}); 

function renderGrid(){ 

var blocks = document.getElementById("content").children; 
var pad = 20, cols = 3, newleft, newtop; 
for(var i = 1; i < blocks.length; i++){ 
    if(i % cols == 0){ 
     newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad; 
     blocks[i].style.top = newtop+"px"; 
    }else{ 
     if(blocks[i-cols]){ 
      newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad; 
      blocks[i].style.top = newtop+"px"; 
     } 
     newleft = (blocks[i-1].offsetLeft + blocks [i-1].offsetWidth) + pad; 
     blocks[i].style.left = newleft+"px"; 
    } 
    } 
} 
window.addEventListener("load", renderGrid, false); 
window.addEventListener("resize", renderGrid, false); 

content.php

<?php 
include ("connect.inc.php"); 
$userinput = $_POST['name']; 
$query = "SELECT * FROM xxx WHERE xxx LIKE '%$userinput%'"; 
$result = mysqli_query($db_link, $query) or die(mysqli_error($db_link)); 
while($row = mysqli_fetch_assoc($result)){ 
?> 

<article> 
    <?php echo $row['xxx'];?> 
</article> 

<?php 
} 
?> 

Picture 1 = This is what it does. (When I submit Russia, my query will get me two results, but as you can see, these results are now on top each other upon output. This is because the JavaScript is unaware, that I have outputted something.)

あなたのオブジェクト( window)はロードが完了したとき( manualのように)

Picture 2 = This is what it should look like, when outputted. (Now, if I mess with the viewport, such as open inspect, my JavaScript begins to work (window.addEventListener("resize", renderGrid, false);), so my JavaScript works, but not when I output data, but not automatically when I output data.)

+0

したがって、ajaxリクエストが終了した後で明示的に 'renderGrid'を呼び出します。 –

+0

それは最適なソリューションですか? :) –

+0

オプションはありません。 –

答えて

0

loadイベントが発生します。このイベントは、いくつかのAjaxコンテンツを読み込むと起動しません。したがって、renderGridを明示的に呼び出す必要があります:

$.post("content.php", {name: form_search}, function(data){ 
    $('#content').html(data);  
    renderGrid(); 
}); 
+0

うん、それは私の問題を修正した。ありがとう –

関連する問題