简体   繁体   中英

setting attributes of appended HTML to a variable in jquery?

so, i'm working on a backend create/edit/delete page for a blog - it shows a list of articles with an edit and delete button for each. when the edit button for article 'foo' is clicked, these things happen:

  • the div expands and the raw HTML of an edit form is appended inside with jquery append().

  • the DOM has an array of objects, with each object containing the information for one article. the specific object with id 'foo' is fetched and cast to an array 'bar'.

now, what i'm trying to do is to set the values of the appended form to the values within 'bar'. i've tried using .attr(), .val(), but nothing seems to work.

i think the problem might be that i'm doing this all in the same scope. right after my .append() call, i try to access the elements i just appended by ID. is this tripping me up?

within the function, this is how i tried to do it:

$(this).parent().children('#thisone').append("<input id="articletitle">");
$(this).parent().children('#thisone').children('#articletitle').val("my title");

Try building the complete element before you append it:

var $input = $("<input>", { 
    id: "articleTitle",
    value: "my title"
});

$("#thisone").append($input);

Assuming your HTML code will be somewhat like this

<div id="thisone">
    <span id="articletitle">Some Crazy Blog Title</span>
    <a id="edittile" href="#">Edit Title</a>
</div>

Javascript code to question:

$('#edittile').on('click', function() {
    var value = $('#articletitle').text();
    var html = '<form><input type="text" value="'+ value +'">';
    html += '<input type="submit" value="save"></form>';
    $('#articletitle').html(html);
    $(this).hide();
});

I have created a js fiddele code your ref too check it out here: http://jsfiddle.net/4hA6y/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM