我试图看看是否有可能使用jquery来创建动态按钮。按钮将完全相同,但是将特定变量传递给链接到站点或创建站点链接的函数。我不想创建每一个新的列表项目,如果我有超过300个。是否有办法为每个列表项创建一个函数来动态创建按钮?
这是html
<nav id="menu">
<div id="app">
<ul class="List"><li><span>Enter Number below</span>
</li>
<div id="number">
<input type="text" name="number" id="textbox1" value="22984">
</div>
<li><span>Disney</span>
<ul id="programs">
<li><span>Lands</span>
<ul id="10min">
<li><span>Adventureland</span>
<ul id="Adventureland">
<li class="Label"> </li>
<button class="redirect" id="AdventureLand">Open Website</button><br/>
<button class="txtLinky" id="Adventureland">Click Link</button><br/>
<div id="linkified">value</div>
</ul>
</li>
<li><span>Frontierland</span>
<ul id="Frontierland">
<li class="Label"> </li>
<button class="redirect" id="Frontierland">Open Website</button><br/>
<button class="txtLinky" id="Frontierland">Click Link</button><br/>
<div id="linkified">value</div>
</ul>
</li>
<li><span>Fantasyland</span>
<ul id="Fantasyland">
<li class="Label"> </li>
<button class="redirect" id="FantasyLand">Open Website</button><br/>
<button class="txtLinky" id="Fantasyland">Click Link</button><br/>
<div id="linkified">value</div>
</ul>
</li>
<li><span>Tomorrowland</span>
<ul id="Tomorrowland">
<li class="Label"> </li>
<button class="redirect" id="TomorrowLand">Open Website</button><br/>
<button class="txtLinky" id="Tomorrowland">Click Link</button><br/>
<div id="linkified">value</div>
</ul>
</li>
</ul>
</li>
</li>
</ul>
</li>
</ul>这是javascript
$(".redirect").click(function(){
goUrl = 'http://www.example.com/' + $(this).attr('id') + '?referringRepId=' + $("#textbox1").val();
window.location = goUrl;
});
$(".txtLinky").on("click", function () {
var link = 'Copy and paste '+ 'http://teambeachbody.com/shop/-/shopping/' + $(this).attr('id') + '?referringRepId=' + $("#textbox1").val();
$(this).parent().children('#linkified').html(link);
$(this).parent().children('#linkified').linkify({
tagName: 'a',
target: '_blank',
newLine: '\n'
});
$(this).parent().children('#linkified');
});这是jsfiddle http://jsfiddle.net/VFhK9/18/
发布于 2014-07-31 19:52:55
是的,有可能!
首先,我建议修改HTML代码,因为除了UL中的LI之外,其他标记都是错误的.另外,对于不同的元素,您使用的不是唯一的ID..。
忽略HTML格式的所有问题,下面的示例将遍历以'land‘结尾的is的所有UL元素,并在其中添加带有两个按钮的新LI元素:
$('ul[id$="land"]').each(function() {
var ul = this;
$(ul).append(
$(document.createElement('li'))
.append(
$(document.createElement('button'))
.addClass('redirect')
.text('Open Website')
.click(function() {
var goUrl = 'http://www.example.com/' + $(ul).attr('id') + '?referringRepId=' + $("#textbox1").val();
window.location = goUrl;
})
)
.append(
$(document.createElement('button'))
.addClass('txtLinky')
.text('Click Link')
.click(function() {
// add other functionality here...
})
)
)
});我觉得一般的想法很清楚..。只需构建包含最少所需信息的HTML,并使用jQuery动态添加其余内容。
这里是更新的小提琴。
https://stackoverflow.com/questions/25064852
复制相似问题