我正在尝试创建一个样式切换器。我想做的是在我的页面上为每种颜色有一些框。类似于以下内容:
<table>
<tr>
<td><a href="#" Title="Style A" onclick="javascript:changeStyle("/Content/Themes-jQuery/humanity/jquery-ui-1.8.17.custom.css")>A</td>
<td><a href="#" Title="Style B" onclick="javascript:changeStyle("/Content/Themes-jQuery/vader/jquery-ui-1.8.17.custom.css")>B</td>
</tr>
</table>然后在函数中,我想这样做:
$("link[title='jquery-ui-theme']").attr("href", xxx );其中xxx是传递给函数的参数。
有没有人能给我一些建议,告诉我如何从<a>链接内部调用函数,以及函数的定义应该是什么样子。
另外,有没有更好的方法可以使用更多的jQuery来做这件事呢?使用DIVs而不是table/row会更好吗?
发布于 2012-02-14 11:45:26
是的,有更好的方法可以做到这一点。例如,您可以使用以下标记:
<ul class="style-switcher">
<li><a href="#" data-style="humanity">Humanity</a></li>
<li><a href="#" data-style="vader">Vader</a></li>
</ul>和这个JavaScript:
$(".style-switcher").on('click', 'a', function(e) {
var style = $(this).attr('data-style');
changeStyle('/Content/Themes-jQuery/' + style + '/jquery-ui-1.8.17.custom.css');
e.preventDefault();
});要使其看起来相同,您可以使用此CSS:
.style-switcher {
overflow: auto;
margin: 0;
padding: 0;
}
.style-switcher > li {
float: left;
list-style-type: none;
width: 10em; /* You should probably adjust this. */
}
.style-switcher > li > a {
display: block;
width: 10em; /* You should probably adjust this. */
}JSFiddle上的 。
更好的做法是将href更改为某个位置,以便禁用脚本的用户可以进行样式切换。
发布于 2012-02-14 11:44:52
我认为如果你这样做会更干净:
<table id="themes">
<tr>
<td><a href="/Content/Themes-jQuery/humanity/jquery-ui-1.8.17.custom.css" Title="Style A">A</td>
<td><a href="/Content/Themes-jQuery/vader/jquery-ui-1.8.17.custom.css" Title="Style B" >B</td>
</tr>
</table>
<script type='text/javascript'>
$('#themes a').on('click', function(event){
event.preventDefault();
$("link[title='jquery-ui-theme']").attr("href", $(this).attr('href') );
});
</script>发布于 2012-02-14 11:44:48
有一个更好的方法可以做到这一点:
$('a.clickme').click(function() {
alert($(this).data('style'));
});您的链接布局将如下所示:
<a href="#" Title="Style A" class="clickme" data-style="humanity">A</a>http://jsfiddle.net/GtcP6/
https://stackoverflow.com/questions/9271387
复制相似问题