简体   繁体   English

在jQuery元素上调用用户定义的javascript函数

[英]Calling user defined javascript function on jQuery element

I've been trying to call a user defined JavaScript function on a jQuery element, and though I've seen several topics on here about it, I'm still having a bit of trouble applying their logics to my situation. 我一直在尝试在jQuery元素上调用用户定义的JavaScript函数,尽管我在这里看到了一些有关它的主题,但是在将其逻辑应用于我的情况时仍然遇到了一些麻烦。 Here's what i've tried so far: 到目前为止,这是我尝试过的:

Javscript & jQuery: Javscript和jQuery:

    $(document).ready(function() {

// JavaScript function     
     nl2br = function (str, is_xhtml) {
            var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>';
            return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
        }



    // jQuery Call
        if ( ! $('.mediaDesc:contains("p")').length || ! $('.mediaDesc:contains("div")').length || ! $('.mediaDesc:contains("span")').length ) {
                nl2br(this);
            }

    }); //end document ready

HTML: HTML:

<div class="mediaDesc">
Hello World!
I am text on a new line soon to have a br tag before me!    
</div>

My goal is to dynamically find div's with a class of mediaDesc to see if their inner content contains html tags such as p,span, or div. 我的目标是动态查找带有mediaDesc类的div,以查看其内部内容是否包含html标签,例如p,span或div。 If not, then apply the nl2br JavaScript function to it. 如果不是,则对其应用nl2br JavaScript函数。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance. 提前致谢。

Based on the current available info, I believe you want something like this: 根据当前的可用信息,我相信您需要这样的东西:

$(".mediaDesc").each(function () {
    if ($(this).find("p").length == 0 || $(this).find("div").length == 0 || $(this).find("span").length == 0)
    {
        $(this).html(nl2br($(this).html()));
    }
});

edit: fixed mis-use of .contains 编辑:修复对.contains

http://jsfiddle.net/s8eNh/ http://jsfiddle.net/s8eNh/

.contains is for searching text within the node. .contains用于在节点内搜索文本。 What you want is: 您想要的是:

$('.mediaDesc').not(':has(p, div, span)').each(nl2br)

if you need to process the node and only call nl2br with text or html then do: 如果您需要处理节点,并且仅使用texthtml调用nl2br,请执行以下操作:

$('.mediaDesc').not(':has(p, div, span)').each(function(){
    nl2br( $(this).html() )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM