开发者

Extracting text from a HTML to be stored as a JS variable, then to be added to a separate HTML's element

Alrite, I have seen other Questions with similar titles but they don't do exactly what Im asking. I have 2 x HTML documents, one containing my page, one containing a element with a paragraph of text in it. As-well as a separate .js file what I want to do is extract this text, store it as a JS variable and then use jQuery to edit the contents of an element within the main page. This is the conclusion I came to but it didnt work as expected, im not sure if it is me making a syntax error or if i am using the wrong code completely:

$(document).ready(function(){
var c1=(#homec.substring(0)) 
     // #homec is the container of the text i need 
    $(".nav_btn #1").click(function(c1){ 
         $(".pcontent span p") .html(+c1)} 
);

});

i know +c1 is most probably wrong, but i have been struggling to find the syntax on this one. thankyou in ad开发者_Python百科vance :D


var c1=(#homec.substring(0)) will throw an error because #homec is not a valid variable name, is undefined, and does not have a property function called substring. To get the html of an element with an id of homec, use the html method:

var c1 = $("#homec").html(); 

c1 should not be an argument of the click function because it is defined in the parent scope. +c1 is unnecessary because you do not need to coerce c1 to a number.

If you are trying to add content to the end of the paragraph, use the append method:

$(".pcontent span p").append(c1)

That means you should use this code instead:

$(document).ready(function() { 
  var c1 = $("#homec").html();
  $(".nav_btn #1").click(function() {  
     $(".pcontent span p").append(c1)
  }); 
});

P.S. Numbers are not valid ID attributes in HTML. Browsers support it, so it won't make anything go awry, but your pages won't validate.


Try this:

$(".nav_btn #1").click(function(c1){           
    var para = $(".pcontent span p");
    para.html(para.html() + c1);
    });


The JQuery text() function will allow you to get the combined text contents of each element in the set of matched elements, including their descendants. You can then use the text(value) function to set the text content of your target paragraph element. Something like this should suffice:

$(document).ready(function() {
    var c1 = $("homec").text();
    $(".nav_btn #1").click(function() { 
        $(".pcontent span p").text(c1);
    });
});

See the JQuery documentation for more details on the text() function. If you need to capture the full structure of the other document, then try the html() function instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜