2016-05-27 12 views
-1

新しい無線タイプを.append()しようとしましたが、新しい無線機をクリックして新しい機能を開始しましたが、これをしないでください。 これは私のコードです:JQueryの.append()と新しい要素の "on click"を作成

HTML:

<label>Where take the photo?</label> 
     <input type="radio" id="MX0" name="wherePhoto" value="MX0"> México 
     <input type="radio" id="EX0" name="wherePhoto" value="EX0"> Foreign 
<div id="newPhoto"></div> 

<div> 
     <a class="btn btn-default" onclick="addPhoto();" id="btnAdd">Add photo</a> 
</div> 

JS:

var id = 1; 
function addPhoto() { 
    var $newPhoto='<div><label>Where take the photo?</label><input type="radio" id="MX' +id+ '"name="wherePhoto' + id + '" value="MX"> México<input type="radio" id="EX' +id+ '" name="wherePhoto' +id+ '" value="EX"> Foreign <div>'; 

    $('#newPhoto').append($newPhoto); 
    id++; 
} 

$('[id^=MX]').click(function() { 
    alert("hello MX");   
}); 

$('[id^=EX]').click(function() { 
    alert("hello EX");  
}); 

だから私は新しいラジオ(MX1)の際にクリックし、アラートを送信しようと

感謝任意のヘルプ

+0

読む[ 'イベントdelegation'](https://learn.jquery.com/events/event-delegation/)答えを、私を助けるため – Rayon

+0

感謝イベント委任の詳細を理解してください – Lubelmont

答えて

0

約012を読む

について

var id = 1; 
 

 
function addPhoto() { 
 
    var $newPhoto = '<div><label>Where take the photo?</label><input type="radio" id="MX' + id + '"name="wherePhoto' + id + '" value="MX"> México<input type="radio" id="EX' + id + '" name="wherePhoto' + id + '" value="EX"> Foreign <div>'; 
 
    $('#newPhoto').append($newPhoto); 
 
    id++; 
 
} 
 

 
$('#newPhoto').on('click', '[id^=MX]', function() { 
 
    alert("hello MX"); 
 
}); 
 

 
$('#newPhoto').on('click', '[id^=EX]', function() { 
 
    alert("hello EX"); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<label>Where take the photo?</label> 
 
<input type="radio" id="MX0" name="wherePhoto" value="MX0">México 
 
<input type="radio" id="EX0" name="wherePhoto" value="EX0">Foreign 
 
<div id="newPhoto"></div> 
 
<div> 
 
    <a class="btn btn-default" onclick="addPhoto();" id="btnAdd">Add photo</a> 
 
</div>

+0

答えをくれてありがとう、イベント委任の詳細を理解するのを助けてくれました – Lubelmont

+0

@ルーベルモント、お手伝いを!親切に[受諾とアップ - 投票](http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow)目的を解決した最高の解決策:) __Happyコーディング!__ – Rayon

関連する問題