2014-11-23 68 views
0

我正在尝试使用changePost函数更改x的值。JavaScript使用onclick()函数更改值

当changePost函数被触发时,它应该将x的值更改为 对应的posts [i]。

var x = 0; var title = posts[x].title, date = posts[x].date, content = posts[x].content, author = posts[x].author; 
     <article> 
     <h2>$title</h2> 
     <small>$date.format()</small> 
     <p>$content</p> 
     <cite>$author</cite> 
     </article> 

     for(var i in posts) { var title = posts[i].title, date = posts[i].date, content = posts[i].content, author = posts[i].author; 
     <article> 
     <h3 onclick="changePost()">$title</h3> 
     <small>$date.format()</small> 
     </article> 
     } 
    </aside> 

    function changePost(){ var x = i; }; 

谢谢。

+0

嗨,你有没有这方面的一个JS小提琴? – 2014-11-23 10:26:38

+0

另外,请将JS和标记分开。 – Terry 2014-11-23 10:31:40

+0

Js小提琴:http://jsfiddle.net/bcq7580s/ – user3865871 2014-11-23 10:33:33

回答

1

你的问题不只是改变x的价值,你必须重新呈现模板,每次你改变x

var main_template = document.getElementById('mainTemplate').innerHTML; 
function changePost(x) { 
    main.post_id = x; 
    document.getElementById('main').innerHTML = T(main_template, main); 
} 

这里的小提琴:http://jsfiddle.net/bcq7580s/5/

替代方法是使所有的帖子,通过CSS隐藏所有,然后当用户点击链接,隐藏所有可见的帖子,然后只显示一个用户选择。

0

我知道你想通过点击下一个按钮来浏览帖子数组。我建议您将发布模板,浏览后功能以及必须触发发布内容更改的事件分开。

要创建模板,您可以使用Underscore's template function。或者EJS。可能还有很多其他模板库。

对于操纵dom我会建议jQuery,但你可以不做。

确保在尝试访问页面中的元素之前加载所有HTML。

访问this JS Fiddle

的标记:

<div id="post"></div> 
<a href="#" id="next">next</a> 

代码:

// A simple wrapper for your posts so your index variable cant be overwritten 
// by some other peace of code 
var posts = (function() { 

    // The template for the posts, using Underscore's template function 
    var tpl = _.template("<h2><%= title %></h2><p><%= content %></p>"); 

    // The index of the current post 
    var index = 0; 

    // The array of posts 
    var posts = [ 
     {title:"Title 1", content:'Bla bla lorem'}, 
     {title:"Title 2", content:'Bla bla ipsum'}, 
     {title:"Title 3", content:'Bla bla dolor'}, 
     {title:"Title 4", content:'Bla bla sit'}, 
     {title:"Title 5", content:'Bla bla amet'} 
    ]; 

    // The functions available to the document 
    return { 
     next:function(){ 
      if(++index >= posts.length) { 
       index = 0; 
      } 
      return tpl(posts[index]); 
     }, 
     load:function(){ 
      return tpl(posts[index]); 
     } 
    } 
}()); 

// Use of your posts object by the html document 
document.getElementById('post').innerHTML = posts.load(); 
document.getElementById('next').onclick = function(){ 
    document.getElementById('post').innerHTML = posts.next(); 
}