2013-04-03 25 views
1
var count=0; 
    function createOne() { 
     var divTag = document.createElement("div"); 

动态创建的div如何获得动态创建的JavaScript div id由jquery和存储在PHP?

 var br= document.createElement("br"); 
     count++; 
     divTag.id = "div1"+count; 

编号增量1

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

     divTag.style.margin = "0px auto"; 
     divTag.style.width="430px"; 
     divTag.style.height="35px"; 
     divTag.style.background="olive"; 
     divTag.className = "dynamicDiv"; 

     divTag.innerHTML = "This HTML Div tag created " 
          + "using Javascript DOM dynamically."; 

     document.body.appendChild(divTag); 
      document.body.appendChild(br); 
    } 

>需要使用Jquery保存在php中。

<body> 
    <h1 align="center"> 
    Click it 
    <input type="button" id="dev" onClick="createOne()" value="GET"> 
    </h1> 
</body> 
+0

在什么情况下,你节省的jQuery在PHP中DIV内容? – Neo

回答

1

如果您使用jQuery然后使用它。将你的函数转换成jQuery并使用jQuery的ajax函数。

的JavaScript

jQuery(function($){ 

    $('#dev').click(function(){ createOne(); }); 

    window.count = 0; 
    function createOne() { 

     var new_id = 'div1' + (++count); 

     $('body').append('<div class="dynamicDiv" id="' + new_id + '" style="margin: 0px auto; width: 430px; height: 35px; background-color: olive;">This HTML Div tag created using Javascript DOM dynamically.</div><br/>');  

     $.get('/div-id-saver.php', { 'id': new_id }, function(response){ 
      console.log('post response:' + response); 
     }); 

    } 

}); 

HTML

<body> 
    <h1> 
    Click it 
    <input type="button" id="dev" value="GET"> 
    </h1> 
</body> 

更多信息:http://api.jquery.com/category/ajax/shorthand-methods/

1

**使用jQuery **

// Within your createone() function 

// Location of your PHP file 
var url = 'savemyvar.php'; 

$.post(url, { div : divTag.id }).success(function(data, status, xhr) 
{ 
    // Do something on success 
}).error(function(data) 
{ 
    // Do something on error 
}); 

Info on $.post a helper function for $.ajax

$.ajax documentation 这将您divTag对象发送到PHP脚本,您可以使用

$_REQUEST['div'] 

到访问。

+0

传递DOM对象'divTag'不是OP的意图。 – iambriansreed

+0

身份证通过,而不是...我敢肯定,当之无愧地downvote ... –

+0

改变后的un-downvoted。这是[显然不正确](http://stackoverflow.com/privileges/vote-down)。 – iambriansreed

1

在您的createOne()函数中,您可以将AJAX回传到PHP脚本,并通过您刚刚创建的元素的ID。

您可以找到您还没有指定你想要的信息或者所以这应该有助于上手做什么上JQuery's AJAX here

更多信息。

+0

有兴趣知道为什么有人投下了这个... – webnoob

1

我建议你阿贾克斯

createOne = function() { 
    var $div = $('#div1'+count); 
    $.ajax({ 
     type: "POST", 
     url: "some.php", 
     data: { id: "div1"+count, html: $div.html() } 
    }).done(function(msg) { 
     alert("Data Saved: " + msg); 
    }); 

} 
1

发布数据在Ajax调用,数据会看起来像:

var mydata = new Array(); 
$("div[id^='div']").each (function(){ 
     mydata.push ({$(this).attr ("id") : $(this).text()}); 
}); 

我使用DIV作为价值的文字,但你可以改变它到您的需求...

+0

+1在我的情况下,你的解决方案很简单,很好。:) – RajeshKdev