Good morning everyone,
I tried to sleep over my problem, but I am stu开发者_Go百科ck at the syntax as I'm relatively new to JavaScript and jQuery.
So, my idea was to clone a phrase like:
<p>
<a href="#" class="myClass">[1]</a>
</p>
This is my code to clone this phrase:
var clone = $("p").clone();
Now I want to add a checkbox to each phrase
var clone = $("p").clone().prepend("<input type='checkbox' id='checked' checked>");
The html-structure looks like:
<p>
<input type="checkbox" checked=" " id="checked">
<a href="#" class="myClass">[1]</a>
</p>
The following is the hardest part for me: I'm trying to achieve an alert with the value of the link, when the checkbox is marked. The value should have no brackets like "[" or "]". I guess that I have to work with regular expressions like replace();
My final aim would be to insert the value of the link into a textarea. But I didn't figure out how to alert the value.
Can you help me?
Looks like:
var clone = $("p").clone().prepend($('<input>', {
id: 'checked',
type: 'checkbox',
checked: 'checked',
change: function() {
if( this.checked ) {
alert( $(this).next('a').text().match(/^\[(\d+)\]$/)[1] );
}
}
})).appendTo(document.body /* or somewhere else */);
Demo: http://jsfiddle.net/WkceQ/
Try:
$('a.go').click(function(){
var $p = $('p');
$p.each(function(){
var checked = ($(this).find('input').is(':checked'));
var result = checked ? ($(this).find('a')[0].innerHTML.replace('[', '').replace(']', '')) : $(this).find('a')[0].innerHTML;
alert(result)
});
return false;
});
DEMO
精彩评论