英文:
How to use jQuery onclick event to wrap a div into a link
问题
我有一个div(id = "big-div"),其中包含一些较小的div。
我想将这个大div包装成一个链接,这样无论用户点击哪里,都会将用户带到页面A,除了一个小div,它会将用户带到页面B。
有点像YouTube视频网格。当我们点击视频网格时,它会带我们到视频页面,除非我们点击频道个人资料图片,它会带我们到频道个人资料。
我想知道这是否可以通过jQuery实现。
我尝试从头创建一个元素,但它没有起作用。
我尝试使用onclick事件,但它也没有起作用。
这是我的代码:
$("#big-div").on("click", function(){
$("<a>")
.attr("href", "https://www.youtube.com")
.appendTo("#big-div");
});
英文:
I have a div (id = "big-div"), within which there are a few smaller div.
I would like to wrap the big div into a link, so wherever the user clicks, it will take the user to pageA, except one small div, which will take the user to pageB.
Kind of like youTube video grid. When we click on a video grid, it takes us to the video page, except when we click on the channel profile picture, it will take us to the channel profile.
I wonder if this is achievable by jQuery.
I tried to create a <a> element from scratch, it didn't work.
I tried to use a onclick event, it didn't work.
Here's my code:
$("#big-div").on("click", function(){
$("<a>")
.attr("href", "https://www.youtube.com")
.appendTo("#big-div");
});
</details>
# 答案1
**得分**: 0
不能你只是使用每个div的点击事件来重定向到你想要的URL吗?
```js
$(document).ready(function() {
$('#myDiv').click(function() {
window.location = 'https://www.youtube.com';
}).addClass('blue-square').append('<div class="red-square">Click me to go to Google</div>');
$('.red-square').click(function(e) {
e.stopPropagation();
window.location = 'https://www.google.com';
});
});
.blue-square {
width: 200px;
height: 200px;
background-color: blue;
display: flex;
align-items: center;
justify-content: center;
}
.red-square {
width: 100px;
height: 100px;
background-color: red;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv" class="blue-square">Click me to go to YouTube</div>
英文:
can't you just use onclick of event of each div to redirect to the url you want
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$(document).ready(function() {
$('#myDiv').click(function() {
window.location = 'https://www.youtube.com';
}).addClass('blue-square').append('<div class="red-square">Click me to go to Google</div>');
$('.red-square').click(function(e) {
e.stopPropagation();
window.location = 'https://www.google.com';
});
});
<!-- language: lang-css -->
.blue-square {
width: 200px;
height: 200px;
background-color: blue;
display: flex;
align-items: center;
justify-content: center;
}
.red-square {
width: 100px;
height: 100px;
background-color: red;
cursor: pointer;
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv" class-"blue-square">Click me to go to YouTube</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论