问题
DEMO
Hi, I have variable called "var node = "Hi Mr", Iam trying to append this value on click of a button, im not sure why its not appending.
I tried using html and text, none worked.
JS:
$(function(){
$('.customerResultIndex').on('click',function(){
openCustomerOverlay();
})
});
function openCustomerOverlay(){
var node = "Hi Mr"
$('.customerPopHeading').text(node)
var overlayContainer =
'<div class="customerOverlayShadow">'+
'<div class="customerOverlay borderRadius10px">'+
'<h2 class="customerPopHeading">-- </h2>'+
回答1:
Create the element first, them after this, set the text... You are setting the text befero creating it.
Put this:
var node = "Hi Mr";
$('.customerPopHeading').text(node);
After this:
$(document).keyup(function(e) {
if (e.keyCode == 27) {
$('.customerOverlayShadow').remove();
}
});
Final result: http://jsfiddle.net/pc2tx1us/3/
回答2:
You cannot append a value like this instead you can concatenate it this way:
'<h2 class="customerPopHeading">--'+ node +'</h2>'+
or you can move this line:
$('.customerPopHeading').text(node);
below this:
$("body").prepend(overlayContainer).focus();
$('.customerPopHeading').text(node);
Fiddle
The element has to be available to make a jQuery selector, here when you prepend in body only then it is available to put the desired text in it.
来源:https://stackoverflow.com/questions/26800685/variable-value-is-not-appending-in-h2-element