开发者

HTML inside of jQuery doesn't work for me?

开发者 https://www.devze.com 2023-01-08 05:25 出处:网络
Simple example: $(document).ready(function(){ $(\'body\').css({\'background-color\': \'#dddddd\', \'font-size\': \'12pt\'});

Simple example:

$(document).ready(function(){
 $('body').css({'background-color': '#dddddd', 'font-size': '12pt'});
 $('table tr:odd').addClass('rowShaded');
 $('<p> Oh my learning jQuery is so fun </p>').addClass('myP');
 $('#myButton').click(function() {
  alert($(this).attr("va开发者_运维技巧lue")); //should display the name of the button
     $('#myTestTable').toggle();
    });


});

$('<p> Oh my learning jQuery is so fun </p>').addClass('myP');

Everything is working fine except that line. Shouldn't it actually show a new paragraph on my page with that text? I dont see it, all it shows is a table in my html and button that I can toggle. I thought you can add HTML elements and jQuery places it in the html file ? My CSS is simple for that element:

.myP{
font-family:verdana;
color:red;
}


Well, you have to tell jQuery where it should be shown in your page, using e.g. appendTo().

Example:

('<p> Oh my learning jQuery is so fun </p>')
.addClass('myP')
.appendTo('#mydiv');

appends the HTML to the element with ID mydiv (meaning the p element is now the last child of #mydiv).


In that line you created a new HTML element and added a class to it. You then have to add it to the DOM.

$('body').append($('<p> Oh my learning jQuery is so fun </p>').addClass('myP'));


$('***').append('<p> Oh my learning jQuery is so fun </p>').addClass('myP');

replace *** with appropriate selecotr


As far as I'm aware that's not how jQuery selectors work; you can get all paras with $('p'), or paras with a given id or class... Check out http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/ for examples of how to reference stuff.

0

精彩评论

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