我有一個動態創建的按鈕,並希望將文本和/或圖像存儲在變量中。 我需要存儲的HTML是兩個按鈕標籤使用jQuery將按鈕HTML存儲在變量中
<button id="test">Update now</button>
因此,在這個例子中我將需要存儲文本更新現在之間的一切。 其他示例在按鈕標記和文本之間有圖標圖像。
這需要在文檔加載時發生。
請有人建議我如何使用jQuery來做到這一點?
感謝
JC
我有一個動態創建的按鈕,並希望將文本和/或圖像存儲在變量中。 我需要存儲的HTML是兩個按鈕標籤使用jQuery將按鈕HTML存儲在變量中
<button id="test">Update now</button>
因此,在這個例子中我將需要存儲文本更新現在之間的一切。 其他示例在按鈕標記和文本之間有圖標圖像。
這需要在文檔加載時發生。
請有人建議我如何使用jQuery來做到這一點?
感謝
JC
$(document).ready(function(){
var buttonVar = $("button").html();
alert(buttonVar);
});
像這樣的事情?
var savedData = $("#test").html();
var buttonText = $('#test').text();
你可能要考慮reading the documentation,但以供參考:
$(function(){
var $buttonHtml = $('#test').html();
});
這將執行在文件準備的功能,$(function(){
是速記爲$(document).ready(function()
。如果你想等到所有img
S和CSS加載完成,使用此:
$(window).on('load',function(){
var $buttonHtml = $('#test').html();
});
這也是在等待整個窗口執行函數之前完成加載。
jQuery(document).on("ready", function() {
var buttonHtml = jQuery("#test").html(); //Where buttonHtml is the variable that will contain your button html
});
//Later on...
console.log("This is the html from my button :" + buttonHtml);
作爲穆拉特貼,如果.text()將是一個更好的選擇,如果你只是在檢索文字... – Guillermo
你甚至不需要jQuery。
var buttonHTML = document.getElementById('test').innerHTML;
謝謝你的回答。 – jeeperscreepers
文字:
var text = $('#test').text();
圖片或文字:
var html = $('#test').html();
無論你使用會進去:
$(document).ready(function() {
});
你可以做這樣的事情
HTML:
<button id="test">
<img class="selective"/>
</button>
JS:
var image=false;
var a= "Update now"
var imageVar="https://scontent-b.xx.fbcdn.net/hphotos-frc3/q71/1157449_10151665223728870_898329738_n.jpg"
if(image){
var imageObj = $('.selective', 'button');
imageObj.attr('src', imageVar).show();
}else{
$('button').text(a);
}
CSS:
.selective{display:'none';}
他我假設你會知道它的圖像或文本。
也許jquery.html? http://api.jquery.com/html/ –
你想閱讀與JavaScript的按鈕的文本? –
我想這個問題是非常相似的[this](http://stackoverflow.com/questions/487056/retrieve-button-value-with-jquery) – Phil