2013-04-03 26 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