![](/img/trans.png)
[英]how to use angluarJS to get the parent element when a button is clicked?
[英]how to get the button's element id when clicked and use it in jquery ui
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$(".dialog").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 400
},
hide: {
effect: "blind",
duration: 400
}
});
$( ".opener" ).on ('click',MyJQFunction);
});
function MyJQFunction() {
$(".dialog").dialog( "open" );
}
</script>
<?php
$x = 0;
while($x < 5){
$x = $x+1;
$did1 = 'dialog'.$x;
$did2 = 'opener'.$x;
?>
<div class = "dialog" id= <?php echo $did1; ?> title=<?php echo $did1; ?>>
<p> <?php echo $did1; ?> </p>
</div>
<button class= "opener" > <?php echo $did2; ?> Contact</button>
<?php
}//end of while loop
?>
我基本上是使用while循環創建一個表。 我為每個按鈕和<p>
分配了特定的ID。 現在,我想獲取此ID,然后單擊按鈕時,顯示特定的<p>
。
但是,當我單擊一個按鈕時,所有按鈕都會同時出現。
如何解決此問題?
您想獲得按鈕之前的對話框,您始終可以使用this
關鍵字在其處理程序內引用按鈕,然后使用prev
來獲取對話框div。 您不一定需要具有已發布結構的ID至少。
嘗試這種方式:
function MyJQFunction() {
$(this).prev(".dialog").dialog( "open" );
//to get the id of the dialog
//$(this).prev(".dialog")[0].id;
}
更新
這將不起作用,因為在單擊按鈕之前創建了jquery對話框,並且將它們放置在主體的底部。 因此,將用於按鈕生成的php代碼更改為:
即,附加data-target
屬性以使用特定ID定位對話框。
<button class= "opener" data-target="#<?php echo $did1; ?>"> <?php echo $did2; ?> Contact</button>
並將您的腳本更改為:
function MyJQFunction() {
$($(this).data('target')).dialog( "open" );
}
完整代碼:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$(".dialog").dialog({
autoOpen: false,
show: {
effect: "blind",
duration: 400
},
hide: {
effect: "blind",
duration: 400
}
});
$( ".opener" ).on ('click',MyJQFunction);
});
function MyJQFunction() {
$($(this).data('target')).dialog( "open" );
}
</script>
</head>
<body>
<?php
$x = 0;
while($x < 5){
$x = $x+1;
$did1 = 'dialog'.$x;
$did2 = 'opener'.$x;
?>
<div class = "dialog" id= <?php echo $did1; ?> title=<?php echo $did1; ?>>
<p> <?php echo $did1; ?> </p>
</div>
<button class= "opener" data-target="#<?php echo $did1; ?>"> <?php echo $did2; ?> Contact</button>
<?php
}//end of while loop
?>
</body>
</html>
您應該像這樣使用數據屬性
<button class= "opener" data-dialog="<?php echo $did2; ?>"><?php echo $did2; ?> Contact</button>
function MyJQFunction() {
var dialog = $(this).attr('data-dialog');
$(dialog).dialog("open");
}
要獲取ID,可以使用.attr('id')或.attr('class')來獲取對象的類。
范例:
<button id='12345'>12345</button>
$('button').on('click',function() {
var id = $(this).attr('id');
alert(id);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.