http://jsfiddle.net/zD99p/

我有以前的jsfiddle。现在,如果将鼠标悬停在“测试”上,您会看到一个方框。您会在html中注意到,用于测试的<a>没有相关性。我要添加什么以防止在没有相关内容的情况下追加到文本上,但是在找到相关内容的情况下仍要追加?

码:

this.screenshotPreview = function(){
        xOffset = 20;
        yOffset = 30;

    $("tr").hover(function(e){
         var text = $(this).find('a').attr('rel');
        $("body").append("<p id='screenshot'>"+ text +"</p>");
        $("#screenshot")
            .css("top",(e.pageY - yOffset) + "px")
            .css("left",(e.pageX + xOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        this.title = this.t;
        $("#screenshot").remove();
    });
    $("a.screenshot").mousemove(function(e){
        $("#screenshot")
            .css("top",(e.pageY - yOffset) + "px")
            .css("left",(e.pageX + xOffset) + "px");
    });
};

// starting the script on page load
$(document).ready(function(){
    screenshotPreview();
});


HTML:

<table>
    <tr><td>content<a rel="Testing this out.  This could be a long description. Blah blah blah. Testing this out.  Testing this out.  This could be a long description. Blah blah blah. Testing this out.  " ></td></tr>
        <tr><td><a>Testing</a></td></tr>
    <table>

最佳答案

将选择器更改为仅具有rel属性的目标元素

$("tr:has(a[rel])").hover(function(e){ ...


FIDDLE

关于javascript - Javascript/Jquery:如果找到rel,则追加数据,否则,不追加数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21221897/

10-11 14:09