My page fetches string data from local SQL and appends it to data-role='listview' as li using function below(simplified version)
function CreateListview{
var temp ='<li><a href="#" class="anchor">String Here</a></li>';
$("#<ul>-selector").append(temp).listview("refresh");
}
well, it works fine so I binded a click event for the anchor(class='.anchor')
$(document).on('vclick', '.anchor', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR
$(document).on('vclick', '#ul-selector > a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR
$(document).on('vclick', '#ul-selector > li a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
OR even
$(document).on('vclick', 'a', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
But nothing works I double-checked if click event on other elements works by using the function below on dynamically added li and it sometimes works and sometime doesn't.
I don't know why it works randomly,
but I checked that click events are fired on some other dynamically added elements.
$(document).on('vclick', '#ul-selector > li', function(e){
alert("<li> CLICKED");
});
When it comes to binding click function to dynamically added anchors , the function won't be fired.. could it be a bug? or am I writing codes wrong?
Can you give me a working example binding click event to dynamically added anchor?
It seems works fine for me.
function CreateListView() { var temp ='<li><a href="#" class="anchor">String Here</a></li>'; $("#selector").append(temp).listview("refresh"); } $(document).on('vclick', '.anchor', function(e){ e.preventDefault(); alert("ANCHOR CLICKED"); }); $("#createLi").on("vclick", function(){ CreateListView(); alert("test"); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script> <div id="content"> <ul id="selector"> </ul> </div> <input id="createLi" type="button" value="create li"/>
Am I missing something?
bind the event after you append the html like this
function CreateListview{
var temp ='<li><a href="#" class="anchor">String Here</a></li>';
$("#<ul>-selector").append(temp).listview("refresh");
$("#<ul>-selector > li").on("click",function(){
alert("<li> CLICKED");
});
}
check this fiddle you can apply the same logic here
You're not listening to the click
event but vclick
(???).
$("yourUl").on('click', '.anchor', function(e){
e.preventDefault();
alert("ANCHOR CLICKED");
});
I found the solution.
Problem : with cordova, 'click' on anchor doesn't fire function even with e.preventDefault(); Rather, 'touchstart' works fine.
Solution : 'click' -> 'touchstart' to work on devices
$(document).on('touchstart', '#anchor-selector', function(){
alert("touch");
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.