gpt4 book ai didi

javascript - 如何获取listview选定的id和href文本?

转载 作者:行者123 更新时间:2023-11-28 19:59:18 25 4
gpt4 key购买 nike

我有一个动态 ListView ,其 ID 和文本是来自服务器的动态。

为了简单起见,让我们这样说:

<ul id="productslist" data-role="listview" data-inset="true">
<li data-role="list-divider">Products</li>
<li id="123"><a href="" onclick="check();">#copper 1</a></li>
<li id="124"><a href="" onclick="check();">#copper 2</a></li>
</ul>

我需要获取列表 ID 和产品名称。 (我不知道 id 值,因为它是动态的)

有什么建议吗?

    <!DOCTYPE html> 
<html>
<head>
<title>Testing</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script>

$(document).on("pageinit","#test1",function(){

});

$(document).on("pagebeforeshow","#test1",function(){

//dynamic list with


});

function check(){
var href = $(this).attr('href');
var id = $(this).parent().attr('id');

alert('href :'+id+' ,value:'+id);
};

</script>
</head>
<body>

<div data-role="page" id="test1">
<div data-role="header">
<h1 style="white-space: normal;margin-left:60px;" id="headertitle"></h1>
<a href='menu.html' class='ui-btn-right' data-icon='home' data-theme="a" >Home</a>
</div><!-- /header -->

<div data-role="content">
<h4>List #</h4>

<ul id="productslist" data-role="listview" data-inset="true">
<li data-role="list-divider">Products</li>
<li id="123"><a href="" onclick="check(this);">#copper 1</a></li>
<li id="124"><a href="" onclick="check(this);">#copper 2</a></li>
<li id="125"><input type="button" value="#copper 3" onclick="check();"></li>
</ul>

<input type="button" onclick="openProduct('data');" value="Click"/>

</div><!-- /content -->

<div data-role="footer" data-position="fixed">
<h4></h4>
</div><!-- /footer -->

</div><!-- /page -->
</body>
</html>

最佳答案

使用.on()

$('#productslist').on('click','a',function(e){
e.preventDefault();//stop default behavior of anchor tag
var href = $(this).text();
var id = $(this).parent().attr('id'); //get parent li id
});

<小时/> Fiddle Demo

onclick="check(this);"

<小时/>将此代码放在页面的头部或末尾

function check(el) {
var txt = $(el).text();
var id = $(el).closest('li').attr('id');
alert('id : ' + id + ' , value: ' + txt);
};

关于javascript - 如何获取listview选定的id和href文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21942987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com