2015-12-15 64 views
1

我有预标记之间的一些代码,我要赶人与onclick事件的代码 我的HTML结构如下图所示:如何将一个唯一的ID添加到onclick事件

<div class="Message"> 
    <div class="surroundpre"> 
    <span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span> 
    <pre class="CodeBlock id="id22015640"> 
     <!-- code goes her --> 
    </pre> 
    </div> 
</div> 

预元素和与类surroundpre的div是由javascript创建的。 用于预的唯一ID:

$('pre').each(function(){ 

    if ($(this).attr('id') == undefined){ 
     $(this).attr('id','id'+Math.floor((Math.random() * 99999999) + 1)) 
    } 
}); 

与surroundpre DIV的是象下面这样创建的:

$('.Message .CodeBlock', this).wrap('<div class=surroundpre></div>'); 

跨距与PHP变量创建的:

$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, \\\'id1\\\')">[Select and Copy]</span><br />'; 

结合:

$('.surroundpre').prepend('$SelectButton'); 

我的问题:在php变量中的id1应替换为与pre标签中相同的唯一标识。 我该如何做到这一点? 或者还有其他方法来实现这一点?

+0

使用'random'生成唯一的ID可能不如简单的计数器更可取。 IE'var nextUniqueIDCounter = 0;'然后'$(this).prop('id','id'+ nextUniqueIDCounter ++);' – teynon

+0

你说'php变量'...是'$ SelectButton =' [Select and Copy]
';'在PHP中生成?你打电话过得怎么样?它是否在页面加载之前被调用? – teynon

+0

是的,所有这些代码都在公共函数中;和javascript是在.livequery(函数()一个PHP变量的大字符串:$结果=“jQuery(文档).ready(函数($){.....等等...... – nuet

回答

0

这可能会为你工作,做一些变化,首先是在PHP:

$SelectButton = '<span class="control-copytextarea" onclick="return fieldtoclipboard.copyfield(event, this.getAttribute(\"data-block-id\"))">[Select and Copy]</span><br />'; 

然后在JS:

$('pre').each(function(){ 
    var id; 
    if ($(this).attr('id') == undefined){ 
     id = 'id'+Math.floor((Math.random() * 99999999) + 1); 
     $(this).attr('id',id); 
     $(this).prev('span').attr('data-block-id',id); 
    } 
}); 

现在JS生成的ID是在连接到跨度同时创建,当它可用时,并且预生成(在PHP中)onclick事件可以在需要时访问它(只要这是在ID设置代码运行之后)。

相关问题