如何将PHP中的值传递给javascript函数?

时间:2013-05-29 02:59:51

标签: html

    <p align="left">
        <b>Click this button to create div element dynamically:</b>

 <?php $qry = "SELECT COUNT(*)  AS count From Contact Where CustomerID=$pid";
$result = mysql_query($qry);
$row = mysql_fetch_array($result);
$count = $row['count'];
echo  $count;
if($count >= 6)
{
?>
    <input id="btn1" type="button" value="create div" onClick="popup();" />
<?php
}
else
{

  $num = 6 - $count ;   
  echo $num;
    ?>
<input id="btn1" type="button" value="create div" onClick="createDiv(<?php echo $num ?>);" />
<?php   
}


 ?>

我想将“$ num”传递给我的创建DIV函数

如果$ num为6,则可以创建6个div,如果$ num为4,则最多只能生成4个div

这是我的createDiv函数

var i=0;
    function createDiv(num)
    {


  if(i < num) {
        var divTag = document.createElement("div");

        divTag.id = "div1"+i;

        divTag.setAttribute("align","left");

        divTag.style.margin = "0px auto";

        divTag.className ="ex";

       divTag.innerHTML = "<img class='myimage' onclick='changeimage(this)' border='0' src='images/white_contact.png' width='60'/><table border='0'><tr><td>Name:</td><td><input type='text'></d></tr><tr><td>Title:</td><td><input type='text'></td></tr><tr><td>Contact:</td><td><input type='text'></td></tr></table>";

        document.getElementById("newdiv").appendChild(divTag)

      }

   i++;
   $( ".ex" ).draggable({containment:'parent',cursor:'pointer',opacity:0.6, });
 $( ".ex" ).droppable({ hoverClass:'border' });

    }

但现在我只能创建一个DIV,为什么会这样呢?

1 个答案:

答案 0 :(得分:0)

您可以稍微清理一下代码并使用处理程序来处理这类事情。

你似乎安装了jQuery(因为你使用的是droppable和draggable)

HTML:

<input type='button' class='div-creator' data-div-id="<? echo $id ?>" value="Click Me">

JAVASCRIPT:

$('body').on("click", '.div-creator', function() {
  var id = $(this).data("div-id");
  // And do whatever else you want to do here.
  // $(this) is the element that was clicked.  id is the div-id in the button tag.
});