如何在HTML onClick事件中将html放在页面元素的前面? [英] How to prepend html into on page element from HTML onClick event?

查看:105
本文介绍了如何在HTML onClick事件中将html放在页面元素的前面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置当用户单击特定元素(一个小问号图标)时动态生成工具提示"弹出窗口的功能.这些工具提示将相对于单击的图标绝对定位.由于网站/信息的性质,我决定希望能够使用html中的onClick事件调用javascript函数,然后再传递一些参数.

I am attempting set up the ability to dynamically generate "tooltip" popups when a user clicks on a specific element (a little question mark icon). These tooltips would be absolutely positioned relative to the icon that was clicked. Due to the nature of the site/information, I've decided I'd like the ability to call a javascript function using the onClick event in the html, then passing it a few parameters.

但是,我对这种开发是陌生的,但是在使它起作用时我遇到了一些问题.我已经将所有html和css放置在适当的位置并设置了适当的样式,但是单击时"没有任何反应.我没有收到任何控制台错误,但似乎并没有正确放置html,这超出了我的能力,无法确定原因.

I am new to this kind of development, however, and I am having some issues getting this to work. I have all the html and css in place and styled appropriately but nothing happens "on Click". I don't get any console errors, but it doesn't appear that the html is being prepended properly, and It is beyond my capability to identify why.

这是我编写的代码.

Javascript/jQuery:

Javascript/jQuery:

function createTooltip(h4, p) {
    $(this).next('.dialog-anchor').prepend('<div class="dialog-container"><div class="tooltip-dialog"><h4>'+h4+'</h4><p>'+p+'</p></div><div class="bg"></div></div>');
};

HTML:

<a class="tooltip" onClick="createTooltip('Test Tooltip', 'blah blah blah blah blah blah blah blah blah')"><div class="dialog-anchor"></div></a>

任何见解或帮助将不胜感激.我仍在学习,指出错误会为我带来很多好处.

Any insight or help would be greatly appreciated. I'm still learning and would benefit a great deal from having my mistakes pointed out.

预先感谢!

推荐答案

由于您使用的是jQuery,如何利用它的侦听器并添加html数据属性?

Since you are using jQuery, how about make it use of it's listeners and add html data attributes?

<a class="tooltip" data-h4="Test Tooltip" data-p="blah blah blah blah blah blah blah blah blah">
    <div class="dialog-anchor">ANCHOR</div>
</a>

一件事也是错误的: $(this).next('.dialog-anchor')-.dialog-anchor.tooltip的子级. next()用于同级,而不是子级.改为使用find.

One thing that is wrong as well: $(this).next('.dialog-anchor') - .dialog-anchor is a child of .tooltip. next() is used when it's siblings, not childs. Use find instead.

$(function () { //jquery document.ready
    $('a.tooltip').on('click', function (e) {
        var $this = $(this);
        e.preventDefault();

        //dialog-anchor is a child of tooltip. NEXT is used when it's siblings
        $this.find('.dialog-anchor').prepend('<div class="dialog-container"><div class="tooltip-dialog"><h4>' + $this.data('h4') + '</h4><p>' + $this.data('h4') + '</p></div><div class="bg"></div></div>');
    });
});

http://jsfiddle.net/dg1t4f8c/3/

这篇关于如何在HTML onClick事件中将html放在页面元素的前面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆