简体   繁体   English

设置附加的HTML属性到jQuery中的变量?

[英]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: 单击文章“ foo”的编辑按钮时,会发生以下情况:

  • the div expands and the raw HTML of an edit form is appended inside with jquery append(). div展开,并使用jquery append()在内部附加编辑表单的原始HTML。

  • the DOM has an array of objects, with each object containing the information for one article. DOM具有一个对象数组,每个对象都包含一篇文章的信息。 the specific object with id 'foo' is fetched and cast to an array 'bar'. 提取ID为'foo'的特定对象并将其转换为数组'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. 我试过使用.attr()、. val(),但似乎没有任何效果。

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. 在我的.append()调用之后,我尝试访问刚由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 假设您的HTML代码会像这样

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

Javascript code to question: 要质疑的Javascript代码:

$('#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/ 我已经创建了一个js fiddele代码,您的引用也可以在这里查看: http : //jsfiddle.net/4hA6y/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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