我有一个链接,可链接到帖子上的用户页面,并且单击该帖子本身会为该帖子打开一个专用页面: $ userid = $ entry ['userid'];
$username = getUserName($userid);
$created_at = DateTime::createFromFormat('Y-m-d H:i:s', $entry['created_at']);
echo "<div class=\"".$class."\" onclick=\"postById(".$entry['id'].")\"><p class=\"info\">Posted by <a class=\"userlink\" onclick=\"userById(".$userid.")\">".$username."</a> on ".$created_at->format('j.n.Y')." at ".$created_at->format('H:i')."</p>";
echo "<h2 class=\"title\">".$entry['title']."</h2>";
echo $entry['content']."</div>";
功能:
function postById(postid) {
let form = document.createElement('form');
form.action = 'post.php'
form.method = 'GET'
form.innerHTML = '<input name="postid" class="hidden" value="' + postid + '">';
document.body.append(form);
form.submit()
}
function userById(userid) {
let form = document.createElement('form');
form.action = 'user.php'
form.method = 'GET'
form.innerHTML = '<input name="userid" class="hidden" value="' + userid + '">';
document.body.append(form);
form.submit()
}
单击该帖子时,它会重定向到其页面。但是,当单击链接时,帖子页面仍然会打开。 userById()
仍然被调用,但是在postById()
之后,据我所知,第一次重定向中断了。
当点击顶部的链接时,如何阻止div识别点击?
Illustration of how it should be绿色= userById()
;橙色= postById()
答案 0 :(得分:0)
尝试将onClick
侦听器的范围限制在您希望它工作的地方
尝试一下
echo "<div class=\"".$class."\"><p class=\"info\"><a onClick=\"postById(".$entry['id'].")\">Posted by </a><a class=\"userlink\" onClick=\"userById(".$userid.")\">".$username."</a> <a onClick=\"postById(".$entry['id'].")\">on ".$created_at->format('j.n.Y')." at ".$created_at->format('H:i')."</a></p>";
答案 1 :(得分:0)
Function postById(postid) {
disableOtherLinks(); //You must define it ;)
...
OR
var called = false;
Function postById(postid) {
if( called ) return false;
called = true;
...
Function userById(userid) {
if( called ) return false;
called = true;
...
答案 2 :(得分:0)
您可以使用event.stopPropagation()
来抑制click事件传播到父元素。 Here's an example,请点击红色以触发div,绿色点击仅用于链接。
对于您的DOM:
echo "<div class=\"".$class."\" onclick=\"postById(".$entry['id'].")\"><p class=\"info\">Posted by <a class=\"userlink\" onclick=\"userById(event, ".$userid.")\">".$username."</a> on ".$created_at->format('j.n.Y')." at ".$created_at->format('H:i')."</p>";
您处理的Javascript:
function userById(event, userid) {
event.stopPropagation();
let form = document.createElement('form');
form.action = 'user.php'
form.method = 'GET'
form.innerHTML = '<input name="userid" class="hidden" value="' + userid + '">';
document.body.append(form);
form.submit()
}